我在用户控件中有文本框,如果对文本框的验证失败,我想创建一个视觉状态。我的代码看起来像这样
<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
被激活
TextBox
没有HasError
属性,所以我们不能直接设置它,我们需要制作HasError
附加属性并检测TextBoxTextChanged
事件,然后检查文本是否有效。
根据您的要求,我们建议使用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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句