鼠标结束时使用Binding c#WPF更改图像

时间:2014-05-30 02:11:46

标签: c# wpf binding

我正在WPF中执行一个程序,它在网格中放置了不同的矩形。它们都有一个图像源绑定,使图像在整个程序中动态变化。它类似于2048.事情是,现在我想让这个矩形在鼠标悬停时改变它的imagesource。就像我已经做了一个图像源绑定我无法弄清楚如何做到这一点。

<ListBox Grid.Row="1" ItemsSource="{Binding Tiles}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border  Background="{Binding Converter={StaticResource BackgroundColor2048Converter}}" Width="106.25px" Height="106.25px" CornerRadius="3"  BorderThickness="1" VerticalAlignment="Stretch" Focusable="False" HorizontalAlignment="Stretch" Margin="7">
                        <Rectangle Width="104.25px" Height="104.25px" MouseEnter="Rectangle_MouseEnter" MouseLeave="Rectangle_MouseLeave" >
                            <Rectangle.Fill>
                                <ImageBrush ImageSource="{Binding Converter={StaticResource ImageBackgroundColor2048Converter}, Mode=OneWay}"/>
                            </Rectangle.Fill>
                        </Rectangle>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

这是关于矩形的xaml代码。 imagesource转换器工作,用于在游戏过程中更改图像。但是现在我想在mouseenter事件触发时更改该图像。那就是我完全迷失的地方,如何去做。

1 个答案:

答案 0 :(得分:1)

您可以通过触发器执行此操作:

 <Rectangle Width="104.25px" Height="104.25px" MouseEnter="Rectangle_MouseEnter" MouseLeave="Rectangle_MouseLeave" >
    <Rectangle.Style>
        <Style TargetType="{x:Type Rectangle}">
            <Setter Property="Fill" >
                <Setter.Value>
                        <ImageBrush ImageSource="{Binding Converter={StaticResource ImageBackgroundColor2048Converter}, Mode=OneWay}"/>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="Rectangle.IsMouseOver" Value="True">
                    <Setter Property="Fill" >
                        <Setter.Value>
                             <!-- Whatever you want here -->
                            <ImageBrush ImageSource="{Binding MouseOverImageUri}" /> 
                        </Setter.Value>
                    </Setter>
                </Trigger>
        </Style>
    </Rectangle.Style>
</Rectangle>

请注意,您必须通过样式设置默认值。原因是触发器覆盖样式,但直接应用的属性覆盖触发器。在这种情况下,您希望触发器获胜。

相关问题