更改 TextBox 的默认 ValidationRule 错误行为
Change the default ValidationRule error behavior of a TextBox
我为我的 TextBoxes
创建了自定义 ControlTemplate
,但我无法设法覆盖 ValidationRule 错误的默认行为。
TextBox
边框刚刚变成红色,我找不到在哪里覆盖它。
我想在我的 ControlTemplate
中做的事情是这样的:
<EventSetter Event="HasError" Handler="TextBox_HasErrors"/>
在我后面的代码中:
private void TextBox_HasErrors(...)
{
//Change few things in my TextBox
}
因为我覆盖了 TextBox
的默认值 ControlTemplate
,我有这个 ScrollViewer x:Name="PART_ContentHost"
,我认为它负责边框着色,但我不知道如何以及在哪里改变
其实我对textBox的使用是这样的:
<TextBox Tag="Email">
<TextBox.Text>
<Binding Path="Email" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<local:TextBoxEmailValidationRule Domain=".com"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
有人知道我如何改变红色边框的行为吗?
红色边框是在控件的默认Validation.ErrorTemplate
中定义的。您可以通过将附加的 属性 设置为自定义 ControlTemplate
:
来轻松创建自己的错误模板
<TextBox Tag="Email">
<TextBox.Text>
<Binding Path="Email" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<local:TextBoxEmailValidationRule Domain=".com"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
<Validation.ErrorTemplate>
<ControlTemplate>
<StackPanel>
<!-- Placeholder for the TextBox itself -->
<AdornedElementPlaceholder x:Name="textBox"/>
<TextBlock Text="{Binding [0].ErrorContent}" Foreground="Red"/>
</StackPanel>
</ControlTemplate>
</Validation.ErrorTemplate>
</TextBox>
请参阅 this 博客 post 了解有关此内容和 WPF 中数据验证的更多信息。
我为我的 TextBoxes
创建了自定义 ControlTemplate
,但我无法设法覆盖 ValidationRule 错误的默认行为。
TextBox
边框刚刚变成红色,我找不到在哪里覆盖它。
我想在我的 ControlTemplate
中做的事情是这样的:
<EventSetter Event="HasError" Handler="TextBox_HasErrors"/>
在我后面的代码中:
private void TextBox_HasErrors(...)
{
//Change few things in my TextBox
}
因为我覆盖了 TextBox
的默认值 ControlTemplate
,我有这个 ScrollViewer x:Name="PART_ContentHost"
,我认为它负责边框着色,但我不知道如何以及在哪里改变
其实我对textBox的使用是这样的:
<TextBox Tag="Email">
<TextBox.Text>
<Binding Path="Email" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<local:TextBoxEmailValidationRule Domain=".com"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
有人知道我如何改变红色边框的行为吗?
红色边框是在控件的默认Validation.ErrorTemplate
中定义的。您可以通过将附加的 属性 设置为自定义 ControlTemplate
:
<TextBox Tag="Email">
<TextBox.Text>
<Binding Path="Email" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<local:TextBoxEmailValidationRule Domain=".com"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
<Validation.ErrorTemplate>
<ControlTemplate>
<StackPanel>
<!-- Placeholder for the TextBox itself -->
<AdornedElementPlaceholder x:Name="textBox"/>
<TextBlock Text="{Binding [0].ErrorContent}" Foreground="Red"/>
</StackPanel>
</ControlTemplate>
</Validation.ErrorTemplate>
</TextBox>
请参阅 this 博客 post 了解有关此内容和 WPF 中数据验证的更多信息。