1

我有两个内容相同的组合框。不应允许用户两次选择相同的项目。因此组合框的内容(= selectedindex?)不应该相等。

我的第一次尝试是将 selectedindex 与 datatrigger 一起显示/隐藏按钮:

<DataTrigger Binding="{Binding ElementName=comboBox1, Path=SelectedIndex}" Value="{Binding ElementName=comboBox2, Path=SelectedIndex}">
     <Setter Property="Visibility" Value="Hidden" />
</DataTrigger>

似乎无法使用 Value={Binding}。有没有其他方法(如果可能不使用转换器)?提前致谢!

4

2 回答 2

3

选项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();
    }
}
于 2009-10-02T06:06:41.233 回答
0

如果 ComboBoxes 共享相同的 itemsource,则在通过第一个 ComboBox 选择项目时在基础数据对象上设置一个标志。

在第二个组合框中显示的数据对象的数据模板中,编写一个绑定到该属性并执行适当操作的数据触发器。

确保第一个 ComboBox 的绑定是 TwoWay。

于 2010-02-24T00:42:18.253 回答