快速谷歌搜索不会产生可行的重复。我希望这是一个关于WPF错误模板和/或绑定的UpdateSourceTrigger
属性的非常简单的问题。我有点像WPF n00b,所以请耐心等待。
我不能发布代码本身(与工作相关),但这里有一个基本想法:
我在同一组中有一套标准的几个单选按钮。我在其中一个按钮上"附加"了一个文本框,意思是TextBox.isEnabled
数据绑定到其中一个单选按钮的rb.isChecked
。
文本框使用PropertyChanged
触发器验证数据错误。当发生错误时,它会在自身周围绘制一个红色框。
我遇到的问题是,当且仅当单选按钮启用了文本框时,"空文本框"是一种错误情况。当我选择另一个单选按钮时,我需要清除错误框,但它没有。
我的第一个想法是尝试将错误模板中的某些内容绑定到(HasError && IsEnabled)
,但我看不到明确的方法。
我认为除了PropertyChanged
之外,还可能在FocusLost
事件上触发TextBox
(通过UpdateSourceTrigger
)。有办法做到这一点吗?
当然,我们欢迎其他解决方案。
每当调用PropertyChanged
时,验证都将重新运行。这意味着您可以通过引发TextBox
绑定的PropertyChanged
事件来强制重新验证。
由于RadioButton.IsChecked
更改时需要重新验证,因此可以在RadioButton
绑定到的属性的setter上引发TextBox
绑定到的特性的PropertyChanged
。
示例:
class MyViewModel
{
public bool MyRadioButtonIsSelected
{
get { return myRadioButtonIsSelectedBacking; }
set
{
myRadioButtonIsSelectedBacking= value;
OnPropertyChanged("MyRadioButtonIsSelected");
// Force revalidation of MyTextBoxValue
OnPropertyChanged("MyTextBoxValue");
}
}
public string MyTextBoxValue
{
get { return myTextBoxPropertyBackingField; }
set
{
myTextBoxPropertyBackingField= value;
OnPropertyChanged("MyTextBoxValue");
}
}
}
Xaml:
<RadioButton
Content="My Radio Button"
IsChecked="{Binding MyRadioButtonIsSelected}" />
<TextBox
IsEnabled="{Binding MyRadioButtonIsSelected}"
Text="{Binding MyTextBoxValue, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />