选项1
您可以使用 ValidationRules - 它也可以在 XAML 中完成,并且适用于一次性情况。这将是非常本地化的,我不建议这样做,因为该规则不可重用。也许其他人可以提出一个通用规则来包含不同的输入。试试这个。
<ComboBox>
<ComboBox.SelectedValue>
<Binding Path="Whatever" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:ComparisonValidationRule />
</Binding.ValidationRules>
</Binding>
</ComboBox.SelectedValue>
</ComboBox>
也许比较规则看起来像这样,它必须在该规则的代码隐藏中才能看到可视树中的控件。
public class ComparisonValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
if (this.firstComboBox.SelectedIndex == this.secondComboBox.SelectedIndex)
return new ValidationResult(false, "These two comboboxes must supply different values.");
else return new ValidationResult(true, null);
}
}
或者,如果您想在错误模板之外设置一些有趣的东西,您绝对可以使用触发器来完成。
选项 2
使用触发器和转换器。这真的不是太难。这就是我将如何做到的。
<Style x:Key="{x:Type ComboBox}" TargetType="{x:Type ComboBox}">
<Style.Triggers>
<DataTrigger Value="True">
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource EqualsConverter}">
<Binding ElementName="cbOne" Path="SelectedIndex"/>
<Binding ElementName="cbTwo" Path="SelectedIndex"/>
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Background" Value="Yellow"/>
</DataTrigger>
</Style.Triggers>
</Style>
和代码隐藏中的转换器
public class EqualsConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType,
object parameter, CultureInfo culture)
{
if (values[0] is int && values[1] is int && values[0] == values[1])
return true;
return false;
}
public object[] ConvertBack(object value, Type[] targetTypes,
object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}