Search code examples
c#wpfmvvmtriggerscombobox

Trigger event when Combobox contains only one item


I need disable a combobox whenever it contains only 1 item. I spent a fair amount of time reading the documentation on the microsoft website, but I cannot see any trigger for this type of events. Is this possible in a mvvm way?

I have several (~100) comboboxes that share the same style, so I was looking to add the trigger to the style but I cannot find a way to do this.

Any help is appreciated, even if it involves more documentation to read.

<DataGridTemplateColumn Header="D">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox Style="{StaticResource ComboboxStyleD}" HorizontalContentAlignment="Center" SelectedValue="{Binding D[0]}" ItemsSource="{Binding D}" IsSynchronizedWithCurrentItem="False">
            </ComboBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Solution

  • Found an "easy" solution for this in WPF.

            <Style x:Key="ComboboxStyleD" TargetType="{x:Type ComboBox}">
                <Setter Property="TextBlock.Foreground" Value="Red"/>
                <Setter Property="TextBlock.Background" Value="Red"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding D.Count}" Value="1">
                        <Setter Property="IsEnabled" Value="False" />
                        <Setter Property="TextBlock.Foreground" Value="Black"/>
                        <Setter Property="TextBlock.Background" Value="Black"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>