Search code examples
wpfxamltriggerscombobox

How to trigger Setter on change in another element


I have two ComboBoxes as follows:

When the first box selection is 'All' the second box should be hidden using XAML and a trigger.

<StackPanel Orientation="Horizontal">
<ComboBox x:Name="cbxOne" Style="{StaticResource demoStyle}">
    <ComboBoxItem >One</ComboBoxItem>
    <ComboBoxItem >Two</ComboBoxItem>
    <ComboBoxItem >All</ComboBoxItem>
</ComboBox>
<ComboBox x:Name="cbxTwo">
    <ComboBoxItem >1</ComboBoxItem>
    <ComboBoxItem >2</ComboBoxItem>
</ComboBox>
</StackPanel>

I tried this style to do so:

<Style x:Key="demoStyle" TargetType="{x:Type ComboBox}">
    <Style.Triggers>
    <Trigger Property="SelectedValue" Value="All">
                <Setter Property="cbxTwo.Visibility" Value="Collapsed"></Setter>
        </Trigger>
    </Style.Triggers>
</Style>

Solution

  •    <StackPanel>
                <ComboBox Name="cbxOne">
                    <ComboBoxItem>One</ComboBoxItem>
                    <ComboBoxItem>Two</ComboBoxItem>
                    <ComboBoxItem>All</ComboBoxItem>
                </ComboBox>
                <ComboBox>
                    <ComboBoxItem>1</ComboBoxItem>
                    <ComboBoxItem>2</ComboBoxItem>
                    <ComboBox.Style>
                        <Style TargetType="{x:Type ComboBox}">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding Path=SelectedItem.Content, ElementName=cbxOne}" Value="All">
                                    <Setter Property="Visibility" Value="Collapsed" />
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </ComboBox.Style>
                </ComboBox>
            </StackPanel>