我有以下两个包含类似项目列表的组合框。两个组合框不能具有相同的值。
<ComboBox Name="OldEmpNoListBox"
IsReadOnly="True"
ItemsSource="{Binding OldEmpNoCollection}"
SelectedValue="{Binding Model.FieldNameForOldEmpNo, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
HorizontalAlignment="Left"
Width="150"
IsEnabled="{Binding HasItems, RelativeSource={RelativeSource Self}}"
Grid.Row="1" Grid.Column="1">
<ComboBox.Text>
<Binding Path="Model"
UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<vm:FieldNamesValidator ValidatesOnTargetUpdated="True" />
</Binding.ValidationRules>
</Binding>
</ComboBox.Text>
</ComboBox>
<ComboBox Name="OldCompanyListBox"
IsReadOnly="True"
ItemsSource="{Binding OldCompanyCollection}"
SelectedValue="{Binding Model.FieldNameForOldCompany, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
HorizontalAlignment="Left"
Width="150"
Grid.Row="2" Grid.Column="1">
<ComboBox.Text>
<Binding Path="Model"
UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<vm:FieldNamesValidator ValidatesOnTargetUpdated="True" />
</Binding.ValidationRules>
</Binding>
</ComboBox.Text>
</ComboBox>
以下是验证者:
/// <summary>
/// Duplicate Values Validator
/// </summary>
public class FieldNamesValidator : ValidationRule
{
/// <summary>
/// Validate OldEmpNo field name does not match Old Company field name
/// </summary>
/// <param name="value"></param>
/// <param name="cultureInfo"></param>
/// <returns></returns>
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
EmpNoOptionsSettingsModel _empNoOptions = (App.Current.Resources["Locator"] as ViewModelLocator).ParametersEmpNoOptionsViewModel.Model;
// if OldEmpNo field name = Old Company field name
if (_empNoOptions.FieldNameForOldEmpNo == _empNoOptions.FieldNameForOldCompany)
{
return new ValidationResult(false, "Field name for Old Emp No cannot be the same as the field name for Old Company");
}
return ValidationResult.ValidResult;
}
}
验证按预期工作,只是它只对当前正在更改的组合框运行。例如,如果组合框具有相同的值,则每个框都以红色标出。我更改了第一个框并删除了红色,但红色仍保留在第二个框中。有没有办法让两个组合框在其中一个被改变的时候自己验证?
答案 0 :(得分:0)
验证规则在绑定源属性上被触发 改变了事件。
将绑定中的属性名称更改为指向实际属性:
<ComboBox.Text>
<Binding Path="Model.FieldNameForOldEmpNo"
UpdateSourceTrigger="PropertyChanged">
.....
</ComboBox.Text>
和
<ComboBox.Text>
<Binding Path="Model.FieldNameForOldCompany"
UpdateSourceTrigger="PropertyChanged">
.....
</ComboBox.Text>
从这两个属性的setter中,也为其他属性引发属性更改,以便触发相应的验证规则。