我正在创建一个UserControl
,我希望它有一个行为,当用户将鼠标滚轮旋转到它上面时,背景图像会在两个选项之间交替显示。
到目前为止我所拥有的是:
<UserControl x:Class="OI.MR.UserControls.DataControls.ScrollWheel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="400" d:DesignWidth="118">
<UserControl.Background>
<ImageBrush ImageSource="dial1.png" TileMode="None" />
</UserControl.Background>
<UserControl.InputBindings>
<MouseBinding MouseAction="WheelClick" Command="{Binding ScrollTheWheel}"/>
</UserControl.InputBindings>
</UserControl>
和
public partial class ScrollWheel : UserControl
{
private bool _isDial1 = true;
public ScrollWheel()
{
InitializeComponent();
}
private ICommand _scrollTheWheel;
public ICommand ScrollTheWheel
{
get
{
if(_scrollTheWheel == null)
{
_scrollTheWheel = new DelegateCommand(_ => SwitchImage(), _ => true);
}
return _scrollTheWheel;
}
}
private void SwitchImage()
{
if(_isDial1)
{
(Background as ImageBrush).ImageSource = new BitmapImage(new Uri("dial2.png"));
_isDial1 = false;
}
else
{
(Background as ImageBrush).ImageSource = new BitmapImage(new Uri("dial1.png"));
_isDial1 = true;
}
}
}
然而转动方向盘并未改变背景图像。如何更改图像?
答案 0 :(得分:1)
你的datacontext真的不对: 一种可能性:
<UserControl.InputBindings>
<MouseBinding MouseAction="WheelClick"
Command="{Binding Path=ScrollTheWheel, RelativeSource={RelativeSource AncestorType={x:Type view:YourUserControl}}}"/>
</UserControl.InputBindings>
(将类型替换为用户控件的类型)