【发布时间】:2018-10-29 22:12:25
【问题描述】:
我正在创建一个自定义菜单控件,该控件在使用 MVVM 选择或悬停时更改图像(.PNG 文件)。现在,当我选择一个菜单项时,图像会发生变化,但我很难让悬停部分工作。这是我将 ViewModel 分配给 View 的代码:
<DataTemplate DataType="{x:Type viewModel:MyMenuItem}">
<view:MyMenuItemControl/>
</DataTemplate>
这是我的 UserControl 的代码:
<Grid>
<Image Source="{Binding DisplayImage}">
<Image.InputBindings>
<MouseBinding Gesture="LeftClick" Command="{Binding LeftClickCommand}"/>
</Image.InputBindings>
<Image.Style>
<Style TargetType="{x:Type Image}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="IsMouseOver" Value="{Binding Path=IsHovered, Mode=OneWayToSource}"/>
</Trigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
</Grid>
由于 IsMouseOver 属性是只读的,因此无法编译,但我不知道在此触发器发生时如何更新 ViewModel。我对 WPF 和 MVVM 还很陌生,所以如果这有点无知,我深表歉意。我搜索了大约 2 个小时,并没有找到我可以理解并继续前进的答案。
编辑:这是一个似乎也不起作用的选项 2。当我将鼠标悬停在项目上时,这会编译但不会更新图像:
<Grid>
<Image Source="{Binding DisplayImage}">
<Image.InputBindings>
<MouseBinding Gesture="LeftClick" Command="{Binding LeftClickCommand}"/>
</Image.InputBindings>
<Image.Style>
<Style TargetType="{x:Type Image}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Source" Value="{Binding DisplayHoverImage}"/>
</Trigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
</Grid>
我要采用的解决方案:
<Grid>
<Image>
<Image.InputBindings>
<MouseBinding Gesture="LeftClick" Command="{Binding LeftClickCommand}"/>
</Image.InputBindings>
<Image.Style>
<Style TargetType="{x:Type Image}">
<Setter Property="Source" Value="{Binding DisplayImage}"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Source" Value="{Binding DisplayHoverImage}"/>
</Trigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
</Grid>
【问题讨论】:
-
我猜你不需要触发器,而是使用转换器的绑定。然后,您通过将布尔值从
IsMouseOver转换为图像的转换器绑定Source属性。或者,您可以对 MouseEnter 命令做出反应:stackoverflow.com/questions/36221118/…