c# – 绑定到公共源的多个ComboBox,强制执行不同的选择

我正在尝试将多个ComboBox绑定到一个公共源集合,并强制执行一次ComboBox选择后,所选项目将从其他ComboBox中删除.该集合是动态构建的,所以我在代码中进行.

到目前为止,我已尝试以多种方式实现这一点,而我似乎无法想出一些真正有用的东西.

我已经尝试使用默认视图的Filter谓词,但它只传递了该项,我无法知道哪个控件正在执行过滤器(并且它在概念上甚至没有意义).

我已经尝试创建新的CollectionView,但行为最终会有所不同(获取SelectionChange事件,而我之前没有使用默认视图).

几个小时以来我一直在反对这个问题,而且似乎并不想工作.我很感激有经验的WPF帮助我找到一个有效的例子.我真的希望它不会从集合中自动选择项目并开始空白(否则,每个ComboBox将有一个独特的自动选择,这太过于冒昧).

我真的很接近于允许广泛选择并在以后验证它,但这似乎是一个如此简单的概念,具有令人难以置信的难度.

谢谢

解决方法:

不错的问题,我想到了它,我可能会用MultiBinding和相应的ValueConverter接近它,即

<StackPanel>
    <StackPanel.Resources>
        <local:ComboBoxItemsSourceFilter x:Key="ComboBoxItemsSourceFilter"/>
    </StackPanel.Resources>
    <ComboBox Name="cb1">
        <ComboBox.ItemsSource>
            <MultiBinding Converter="{StaticResource ComboBoxItemsSourceFilter}">
                <Binding Path="Emps"/> <!-- Source collection binding -->
                <Binding ElementName="cb2" Path="SelectedItem"/>
                <Binding ElementName="cb3" Path="SelectedItem"/>
            </MultiBinding>
        </ComboBox.ItemsSource>
    </ComboBox>
    <ComboBox Name="cb2">
        <ComboBox.ItemsSource>
            <MultiBinding Converter="{StaticResource ComboBoxItemsSourceFilter}">
                <Binding Path="Emps"/>
                <Binding ElementName="cb1" Path="SelectedItem"/>
                <Binding ElementName="cb3" Path="SelectedItem"/>
            </MultiBinding>
        </ComboBox.ItemsSource>
    </ComboBox>
    <ComboBox Name="cb3">
        <ComboBox.ItemsSource>
            <MultiBinding Converter="{StaticResource ComboBoxItemsSourceFilter}">
                <Binding Path="Emps"/>
                <Binding ElementName="cb1" Path="SelectedItem"/>
                <Binding ElementName="cb2" Path="SelectedItem"/>
            </MultiBinding>
        </ComboBox.ItemsSource>
    </ComboBox>
</StackPanel>
public class ComboBoxItemsSourceFilter : IMultiValueConverter
{
    #region IMultiValueConverter Members

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        var collection = new List<object>((object[])values[0]);
        foreach (var item in values.Skip(1))
        {
            if (item != null) collection.Remove(item);
        }
        return collection;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }

    #endregion
}

因为你在代码中执行此操作后面添加所有这些绑定应该不是什么大问题,只需将所有组合框放入一个列表中,然后就可以迭代它们.转换器可能需要一些调整,因为它假定输入集合(值[0])可以转换为对象[].

这样做的方式令人遗憾地导致许多第一次机会异常,其原因我到目前为止无法确定……

A first chance exception of type ‘System.Runtime.InteropServices.COMException’ occurred in UIAutomationProvider.dll

上一篇:c# – Combobox中的自动完成功能


下一篇:实验十三:界面设计