【问题标题】:How to disable a combox item if it's already selected in another combobox in xaml c#?如果已在 xaml c# 的另一个组合框中选择了组合框项,如何禁用它?
【发布时间】:2016-10-04 00:24:48
【问题描述】:

我有两个组合框绑定到同一个 ObservableCollection 属性,我想知道是否可以禁用组合框中的一个项目,如果它已经在其中一个中被选中?在 wpf 中。谢谢

【问题讨论】:

标签: c# wpf xaml


【解决方案1】:

您可以将 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 中反转每个选定的布尔值,但实际上翻转布尔值可能最好使用转换器执行)

【讨论】:

    【解决方案2】:

    您可以:

    1. 使用以下方式设置 ComboBoxItem 的 IsEnabled 属性:Disallow/Block selection of disabled combobox item in wpf(感谢Kamil 提供链接)
    2. 让它看起来不一样(但仍然可以选择);
    3. 更新第二个列表,以便在第一个列表的选择发生变化时删除选定的选项;或
    4. 事后应用验证(例如,显示错误图标/消息,或者如果两个选择相同,则禁用“提交”按钮)。

    您的选择将仅取决于您想要获得的体验。

    【讨论】:

    • ComboboxItem 的 IsEnabled 属性怎么样?
    • 忘记了。谢谢卡米尔!在任何情况下,描述所需体验对于找到一个好的解决方案都很重要。
    • 我完全同意 :)
    猜你喜欢
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    相关资源
    最近更新 更多