WPF触发器设置子元素

时间:2015-01-02 13:20:41

标签: wpf xaml

我有

<ListBox ItemsSource="{Binding MenuItems}" Background="Transparent" BorderBrush="Transparent">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Button Command="{Binding Action}" BorderBrush="Transparent" Background="Transparent">
                <Grid>
                    <Image Style="{StaticResource MenuImageStyle}" />
                    <TextBlock Text="{Binding Name}" Style="{StaticResource MenuTextStyle}" />
                </Grid>
            </Button>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

样式:

    <Style TargetType="TextBlock" x:Key="MenuTextStyle">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Foreground" Value="#206c8e" />
            </Trigger>
        </Style.Triggers>
    </Style>
    <Style TargetType="Image" x:Key="MenuImageStyle">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Source" Value="Assets/menuButtonHover.png" />
            </Trigger>
        </Style.Triggers>
    </Style>

但我需要在Grid或Button上将鼠标悬停在一起,但我无法弄清楚如何。

我需要这样的东西。这只是解释,无效

    <Style TargetType="Grid" x:Key="MenuGridStyle">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter TargetType="Image" Property="Source" Value="Assets/menuButtonHover.png" />
                <Setter TargetType="TextBlock" Property="Foreground" Value="#206c8e" />
            </Trigger>
        </Style.Triggers>
    </Style>

1 个答案:

答案 0 :(得分:2)

我不确定这是最佳做法,但应该有效。

添加像@PiotrWolkowski这样的名字

<Grid>
    <Image Name="ButtonImage" Style="{StaticResource MenuImageStyle}" />
    <TextBlock Name="ButtonText" Text="{Binding Name}" Style="{StaticResource MenuTextStyle}" />
</Grid>

并像这样修改你的样式触发器

<Style.Triggers>
    <DataTrigger Binding="{Binding ElementName=ButtonText, Path=IsMouseOver}" Value="True">
        <Setter Property="Source" Value="Assets/menuButtonHover.png" />
    </DataTrigger>
    <Trigger Property="IsMouseOver" Value="True">
        <Setter Property="Source" Value="Assets/menuButtonHover.png" />
    </Trigger>
</Style.Triggers>

<Style.Triggers>
    <DataTrigger Binding="{Binding ElementName=ButtonImage, Path=IsMouseOver}" Value="True">
        <Setter Property="Foreground" Value="#206c8e" />
    </DataTrigger>
    <Trigger Property="IsMouseOver" Value="True">
        <Setter Property="Foreground" Value="#206c8e" />
    </Trigger>
</Style.Triggers>