WPF Visibility of a UI element based on combo selection

There are two issues here. First the default visibility should be specified in the style. But even with that it won’t work because the binding on the trigger is comparing a SelectedValue, a ComboBoxItem object with a string object and that will never be equivalent. To keep the example simple, I’ve placed appropriate values in the ComboBoxItem’s Tag properties. Although the actual implementation of the comparison will likely vary based on the specific needs of the app.

    <ComboBox Name="comboMyCombo">
        <ComboBoxItem Tag="Hide">Don't show the label</ComboBoxItem>
        <ComboBoxItem Tag="Show">Show the label</ComboBoxItem>
    </ComboBox>

    <Label>This is my label
        <Label.Style>
            <Style>
                <Setter Property="Label.Visibility" Value="Collapsed"></Setter>
                <Style.Triggers>
                    <DataTrigger  
                        Binding="{Binding ElementName=comboMyCombo, Path=SelectedItem.Tag}" Value="Show">
                        <Setter Property="Label.Visibility" Value="Visible"></Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Label.Style>
    </Label>

Leave a Comment