Создайте VisualState, если проверка не удалась (UWP) - PullRequest
0 голосов
/ 02 мая 2020

У меня есть Textbox внутри Usercontrol, я хочу создать визуальное состояние, если проверка TextBox не удалась. Мой код выглядит следующим образом

<Grid>
    <TextBox Style="{StaticResource ExtendeTextBoxStyle}" PlaceholderText="I'am Active"   HasError="{Binding IsInvalid, UpdateSourceTrigger=PropertyChanged}"  Height="80" Width="300"  x:Name="txtActive"  Text="{Binding TextValue, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" ></TextBox>
</Grid>

Код позади

  public EditTextControl()
    {
        this.InitializeComponent();
        this.DataContext = TV;
    }

    public bool HasError
    {
        get { return (bool)GetValue(HasErrorProperty); }
        set { SetValue(HasErrorProperty, value); }
    }

    /// <summary>
    /// This is a dependency property that will indicate if there's an error. 
    /// This DP can be bound to a property of the VM.
    /// </summary>
    public static readonly DependencyProperty HasErrorProperty =
        DependencyProperty.Register("HasError", typeof(bool), typeof(EditTextControl), new PropertyMetadata(false, HasErrorUpdated));


    // This method will update the Validation visual state which will be defined later in the Style
    private static void HasErrorUpdated(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        EditTextControl textBox = d as EditTextControl;

        if (textBox != null)
        {
            if (textBox.HasError)
                VisualStateManager.GoToState(textBox, "InvalidState", false);
            else
                VisualStateManager.GoToState(textBox, "ValidState", false);
        }
    }

Но это дает мне ошибку во время компиляции

Unknown member 'HasError' on element 'TextBox'  

Что я здесь делаю, и как я могу убедиться, что при сбое проверки текстового поля мой новый VisualState активируется

1 Ответ

1 голос
/ 04 мая 2020

TextBox не имеет свойства HasError, поэтому мы не можем установить его напрямую, нам нужно сделать свойство HasError attach и обнаружить событие TextBox TextChanged, а затем проверить, является ли текст действительным или нет.

По вашему требованию мы предлагаем использовать TextBoxRegex. И используйте XamlBehaviors для вызова VisualState команды.

Например.

<StackPanel>
    <TextBox
        Name="PhoneNumberValidator"
        extensions:TextBoxRegex.Regex="^\s*\+?\s*([0-9][\s-]*){9,}$"
        Background="Red"
        Header="Text box with Regex extension for phone number, validation occurs on TextChanged"
        >
        <Interactivity:Interaction.Behaviors>
            <Interactions:DataTriggerBehavior Binding="{Binding (extensions:TextBoxRegex.IsValid), ElementName=PhoneNumberValidator}" Value="True">
                <Interactions:GoToStateAction StateName="BlueState" />
            </Interactions:DataTriggerBehavior>
            <Interactions:DataTriggerBehavior Binding="{Binding (extensions:TextBoxRegex.IsValid), ElementName=PhoneNumberValidator}" Value="False">
                <Interactions:GoToStateAction StateName="RedState" />
            </Interactions:DataTriggerBehavior>
        </Interactivity:Interaction.Behaviors>
    </TextBox>

    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="AdaptiveVisualStateGroup">
            <VisualState x:Name="BlueState">

                <VisualState.Setters>
                    <Setter Target="PhoneNumberValidator.Background" Value="Blue" />
                </VisualState.Setters>
            </VisualState>
            <VisualState x:Name="RedState">

                <VisualState.Setters>
                    <Setter Target="PhoneNumberValidator.Background" Value="Red" />
                </VisualState.Setters>
            </VisualState>

        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
</StackPanel>
...