【发布时间】:2016-10-04 00:24:48
【问题描述】:
我有两个组合框绑定到同一个 ObservableCollection 属性,我想知道是否可以禁用组合框中的一个项目,如果它已经在其中一个中被选中?在 wpf 中。谢谢
【问题讨论】:
-
好吧,你试过什么?我们需要查看一些代码才能为您提供帮助。
-
请提供一些当前情况的代码,并从代码中解释哪些部分没有按预期工作。
我有两个组合框绑定到同一个 ObservableCollection 属性,我想知道是否可以禁用组合框中的一个项目,如果它已经在其中一个中被选中?在 wpf 中。谢谢
【问题讨论】:
您可以将 ComboBox 项的 IsSelected 属性绑定到一个布尔值,用于标识您的类中的选定状态。
<ComboBox ItemsSource="{Binding Items}">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="IsSelected" Value="{Binding SelectedA, Mode=OneWayToSource}"></Setter>
<Setter Property="IsEnabled" Value="{Binding SelectedB}"></Setter>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
<ComboBox ItemsSource="{Binding Items}">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="IsSelected" Value="{Binding SelectedB, Mode=OneWayToSource}"></Setter>
<Setter Property="IsEnabled" Value="{Binding SelectedA}"></Setter>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
创建一个公开几个布尔值的类
public class MyClass : INotifyPropertyChanged
{
private bool selectedA;
public bool SelectedA
{
get { return !selectedA; }
set { selectedA = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("SelectedA")); }
}
private bool selectedB;
public bool SelectedB
{
get { return !selectedB; }
set { selectedB = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("SelectedB")); }
}
public event PropertyChangedEventHandler PropertyChanged;
}
(在示例中,我只是在 getter 中反转每个选定的布尔值,但实际上翻转布尔值可能最好使用转换器执行)
【讨论】:
您可以:
IsEnabled 属性:Disallow/Block selection of disabled combobox item in wpf(感谢Kamil 提供链接)您的选择将仅取决于您想要获得的体验。
【讨论】: