2012-07-20 67 views
0

我正在創建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; 
     } 
    } 
} 

然而轉動車輪是不會改變的背景圖像。我怎樣才能讓圖像改變?

+1

你嘗試一下輪子呢? - >多數民衆贊成你註冊的事件:MouseAction =「WheelClick」 – fixagon 2012-07-20 11:39:30

+0

你的行動是'WheelClick'不滾動。 – ChrisF 2012-07-20 11:39:54

+0

@ChrisF:[「WheelClick:\t Mouse wheel rotation。」](http://msdn.microsoft.com/en-us/library/system.windows.input.mouseaction.aspx)如果MSDN錯了, d愛知道我應該使用的正確行動。 – 2012-07-20 11:47:29

回答

1

您的datacontext是真的不正確的: 一種可能性:

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

(替換爲您的用戶控件的類型的類型)

+0

完美。謝謝! – 2012-07-20 12:04:55