Search code examples
c#wpfcomboboxbehavior

Behavior for enabling/disabling a WPF ComboBox depending on number of items


Whenever the ItemsSource of a WPF ComboBox changes (i.e. adding or removing elements, or assigning a new Collection), I want it to do the following (pseudo code):

IsEnabled = Items.Count > 1;

if (Items.Count == 1)
    SelectedItem = Items.First();

I'm using MVVM, and I know how to do it in MVVM. But I want to avoid the boilerplate code, and IMHO it is too UI-specific for the ViewModel to care about. So is there a way to specify this in a Behavior<ComboBox>?

I couldn't find a ComboBox event I could subscribe to. If possible, it should work on ObservableCollection as well as ICollectionView or List etc.


Solution

  • You could use a Style with triggers:

    <Style x:Key="customComboBox" TargetType="ComboBox">
        <Style.Triggers>
            <Trigger Property="HasItems" Value="False">
                <Setter Property="IsEnabled" Value="False" />
            </Trigger>
            <DataTrigger Binding="{Binding Items.Count, RelativeSource={RelativeSource Self}}"
                         Value="1">
                <Setter Property="SelectedIndex" Value="0" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
    

    If you for example put this in your App.xaml file, you can use it across the whole application, e.g.:

    <ComboBox ItemsSource="{Binding SomeCollection}" Style="{StaticResource customComboBox}" />