Search code examples
c#xamluwpvisualstatemanager

VisualStateManager.GoToState not working for TextBox (UWP)


I am trying to set VisualState of a TextBox through code.

 <TextBox x:Name="txtbox"  Width="438" Height="56" Style="{StaticResource ExtendeTextBoxStyle}"
             PlaceholderText="{x:Bind PlaceholderText, Mode=OneWay}" ></TextBox>

Codebehind

   private static void HasErrorUpdated(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
         EditTextControl textBox = d as EditTextControl;
        Grid sds = textBox.Content as Grid;
        var mytxt = sds.Children.FirstOrDefault() as Control;

        if (textBox != null)
        {
            if (textBox.HasError)
                VisualStateManager.GoToState(mytxt , "InvalidState", true);

            else
                VisualStateManager.GoToState(mytxt, "ValidState", false);
        }
    }

But this visual state never gets activated. What is wrong here?


Solution

  • VisualStateManager.GoToState not working for TextBox (UWP)

    Please check if GoToState has been called, if not, I suppose you have not implemented INotifyPropertyChanged interface, I viewed your previous question. I found HasError is DependencyProperty, that means that you need bind it with property has implemented PropertyChanged event handler. When you call OnPropertyChanged() method, it will response propertyChangedCallback function.

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName]string name = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
    private bool _hasError;
    public bool HasError
    {
        get => _hasError;
        set
        {
            _hasError = value;
            OnPropertyChanged();
        }
    }
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        HasError = !HasError;
    }