当按钮具有焦点时,更改网格的可见性

时间:2016-11-03 16:48:10

标签: c# wpf

我正在研究WPF应用程序,如果只有一个按钮具有焦点,我想改变网格的可见性。如果有焦点,我有以下代码来更改按钮的背景。我知道如何以编程方式执行此操作,但我想知道如何在XAML中完成相同的操作。

        <Style TargetType="{x:Type Button}">
            <Style.Triggers>
                <Trigger Property="IsFocused" Value="True">
                    <Setter Property="Background" Value="Aqua" />
                </Trigger>
            </Style.Triggers>
        </Style>

1 个答案:

答案 0 :(得分:1)

您可以为Button命名并使用DataTrigger:

<Window 

    ...    

    >
    <Window.Resources>
        <Style TargetType="{x:Type Grid}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsFocused, ElementName=butt}" Value="True">
                    <Setter Property="Visibility" Value="Collapsed" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <StackPanel>
        <Button x:Name="butt">Hide</Button>
        <Grid>
            <Label Background="Yellow">Inside Grid</Label>
        </Grid>
        <Button>Steal focus</Button>
    </StackPanel>
</Window>

修改

<Window 

    ...    

    >
    <Window.Resources>
        <Style x:Key="CollapsedGridStyle" TargetType="{x:Type Grid}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsChecked, ElementName=butt}" Value="True">
                    <Setter Property="Visibility" Value="Collapsed" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <StackPanel>
        <ToggleButton x:Name="butt">Hide</ToggleButton>
        <Grid x:Name="GridA"
              Style="{StaticResource CollapsedGridStyle}">
            <Label Background="Yellow">Grid A</Label>
        </Grid>
        <Grid x:Name="GridB">
            <Label Background="Green">Grid B</Label>
        </Grid>
    </StackPanel>
</Window>