我有一个带有 GroupBox 的表单,其中有许多控件(复选框、文本框和组合框)。
表单绑定到一个在其属性上实现了 IDataErrorInfo 的视图模型,当用户在控件中输入无效值时,IDataInfo 返回无效结果,并且该控件被通常的红色框包围,并显示错误消息在表格的底部。
问题是,GroupBox 旨在指示一组强制值。用户需要选中组中的至少一个复选框。不这样做不是个体控制的错误,而是群体的错误。因此,我在 GroupBox 中添加了一个 BindingGroup,并添加了一个 ValidationRule,如果未选择任何内容,该规则将返回错误。这很好用。如果未选择任何内容,则 GroupBox 将被通常的红色框包围,并且错误消息将显示在表单底部。
我的问题是,如果 GroupBox 中的一个控件验证失败,我会得到两个红色框 - 一个围绕控件,一个围绕 GroupBox。我在表单底部的列表中收到两条错误消息。
如何防止 BindingGroup 报告组中包含的所有内容的错误?
编辑:
一个简单的示例 - 这不显示 Validation.Errors,但您可以看到 StackPanel 突出显示为验证失败,而包含的 TextBox 显示。
XAML:
<Window
x:Class="BugHunt5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BugHunt5"
Title="MainWindow"
Height="350"
Width="525"
>
<GroupBox
Margin="20"
Header="This is my group"
x:Name="MyGroupBox"
>
<StackPanel>
<StackPanel.BindingGroup>
<BindingGroup NotifyOnValidationError="True">
</BindingGroup>
</StackPanel.BindingGroup>
<TextBox
Height="30"
Width="100"
>
<TextBox.Text>
<Binding
NotifyOnValidationError="True"
ValidatesOnDataErrors="True"
Path="MyString"
UpdateSourceTrigger="PropertyChanged"
>
<Binding.ValidationRules>
<local:NoDecimalsValidationRule ValidatesOnTargetUpdated="True"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</StackPanel>
</GroupBox>
</Window>
C#:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel("This should be an integer");
}
}
public class ViewModel
{
public string MyString
{ get; set; }
public ViewModel(string mystring)
{ this.MyString = mystring; }
}
public class NoDecimalsValidationRule : ValidationRule
{
public override ValidationResult Validate(object value,
System.Globalization.CultureInfo cultureInfo)
{
string myString = value as string;
int result;
if (!Int32.TryParse(myString, out result))
return new ValidationResult(false, "Must enter integer");
return new ValidationResult(true, null);
}
}