如何让鼠标滚轮来更改背景图片(How to get mouse wheel to change th

2019-10-17 01:36发布

我创建一个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;   
        }
    }
}

然而转动车轮是不会改变的背景图像。 我怎样才能获得图像的改变?

Answer 1:

您的DataContext真的不正确:一种可能性:

<UserControl.InputBindings>
    <MouseBinding MouseAction="WheelClick" 
        Command="{Binding Path=ScrollTheWheel, RelativeSource={RelativeSource AncestorType={x:Type view:YourUserControl}}}"/>
</UserControl.InputBindings>

(替换为您的用户控件的类型的类型)



文章来源: How to get mouse wheel to change the background image