Search code examples
c#wpfxamldata-bindingcombobox

Can I bind the visibility of a WPF ComboBox control to the presence/absence of items obtained from a Command?


Can I bind the visibility of a WPF ComboBox control to the presence/absence of items obtained from a Command that populates the ComboBox’s ItemsSource property? In a nutshell, in a situation like:

<ComboBox ItemsSource="{Binding MyCommand.Result, Mode=OneWay}" Visibility="..." />

Can I bind the value of the Visibility property to the presence or absence of items inside MyCommand.Result to hide/show it accordingly?


Solution

  • You could use a Style with a DataTrigger that binds to a source property, e.g.:

    <ComboBox ItemsSource="{Binding MyCommand.Result, Mode=OneWay}">
        <ComboBox.Style>
            <Style TargetType="ComboBox">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding MyCommand.Result.Count}" Value="0">
                        <Setter Property="Visibility" Value="Collapsed" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ComboBox.Style>
    </ComboBox>
    

    Or you could bind to the HasItems property of the control itself:

    <ComboBox ItemsSource="{Binding MyCommand.Result, Mode=OneWay}">
        <ComboBox.Style>
            <Style TargetType="ComboBox">
                <Style.Triggers>
                    <Trigger Property="HasItems" Value="False">
                        <Setter Property="Visibility" Value="Collapsed" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </ComboBox.Style>
    </ComboBox>