简体   繁体   中英

How to disable a combox item if it's already selected in another combobox in xaml c#?

I have two combobox bind to the same ObservableCollection proprety, i would like to know if is possible to disable an item in combox if it's already selected in one of them ? in wpf. thx

You can either:

  1. Set the IsEnabled property of the ComboBoxItem using something like this: Disallow/Block selection of disabled combobox item in wpf (Thanks Kamil for the link)
  2. Make it look different (but still selectable);
  3. Update the second list so it removes the selected option when the selection of the first changes; or
  4. Apply validation after the fact (eg show an error icon/message, or disable the "submit" button if the two selections are the same).

Your choice will depend only on the experience you're trying to achieve.

You can bind the IsSelected property of the ComboBox item to a bool identifying a selected state in your class.

 <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>

Create a class which exposes a couple of bools

        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;
    }

(In the example I am simply reversing each selected bool in the getter, but in reality flipping the bool would probably be best performed using a converter)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM