我正在尝试将多个 ComboBox 绑定(bind)到一个公共(public)源集合并强制执行,一旦做出 ComboBox 选择,该选定项目可能会从其他 ComboBox 中删除。该集合是动态构建的,所以我用代码来完成。
到目前为止,我已经尝试通过多种方式实现这一点,但我似乎无法想出真正有效的方法。
我试过使用默认 View 的过滤器谓词,但它只传递项目,而且我无法知道哪个控件正在执行过滤器(而且它在概念上什至没有意义)。
我已经尝试创建新的 CollectionView,但行为最终有所不同(获取 SelectionChange 事件,而我以前没有使用默认 View )。
几个小时以来,我一直在努力解决这个问题,但它似乎就是不想工作。我很感激有 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
}
由于您在代码中执行此操作,所以添加所有这些绑定(bind)应该不是什么大问题,只需将所有组合框放入一个列表中,您就可以遍历它们。转换器可能需要一些调整,因为它假定输入集合 (values[0]
) 可以转换为 object[]
。
遗憾的是,这种做法会导致很多第一次机会异常,其原因我目前无法确定......
A first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in UIAutomationProvider.dll
关于c# - 多个 ComboBoxes 绑定(bind)到一个公共(public)源,强制执行不同的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5737381/