2016-01-22 52 views
12

我想動畫ButtonBackground如果鼠標超過Button用戶控件動畫按鈕的背景

ButtonBackground必然會我在代碼中創建的我UserControl

... Background="{Binding BGColor, Elementname="QButton"}" 

現在後面的自定義依賴屬性,如果我嘗試使用

<Trigger Property="IsMouseOver" Value="True"> 
    <Trigger.EnterActions> 
     <BeginStoryboard> 
      <Storyboard> 
       <ColorAnimation To="LightBlue" 
           Duration="0:0:2" 
           Storyboard.TargetProperty="Background.Color"/> 
      </Storyboard> 
     </BeginStoryboard> 
    </Trigger.EnterActions> 
</Trigger> 
動畫按鈕的背景

我得到一個例外,說:

不能生氣一個不可變屬性(或類似)。

我該如何解決這個問題?

+0

這些[http://blogs.msdn.com/b/mikehillberg/archive/2006/09/26/cannotanimateimmutableobjectinstance.aspx](http://blogs.msdn.com/b/mikehillberg/archive /2006/09/26/cannotanimateimmutableobjectinstance.aspx)可能會幫助[http://stackoverflow.com/questions/14383214/wpf-storyboard-in-style-returning-a-cannot-animate-color-on-an-immutable- OBJ](http://stackoverflow.com/questions/14383214/wpf-storyboard-in-style-returning-a-cannot-animate-color-on-an-immutable-obj) – spaceplane

回答

3

基於邁克Hillberg的大文章約Cannot animate '...' on an immutable object instance

作爲一種變通方法,您可以更新綁定,使刷副本的 Button。這不會影響綁定 - 任何對 窗口前景的更改都會傳播到Button,但 Button將爲本地動畫製作自己的副本。

所以對於你的完整的解決方案應該是這樣的:

<Window x:Class="WpfApplication2.Window3" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:local="clr-namespace:WpfApplication1" 
    .... 
    .... 

Background="{Binding BGColor, Converter={x:Static local:MyCloneConverter.Instance}}" 

這是引用一個IValueConverter的結合,看起來像這樣:

class MyCloneConverter : IValueConverter 
{ 
    public static MyCloneConverter Instance = new MyCloneConverter(); 

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if (value is Freezable) 
     { 
      value = (value as Freezable).Clone(); 
     } 
     return value; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotSupportedException(); 
    } 
} 
0

更改DP(BGCOLOR)本身來改變背景。

<Button.Triggers> 
    <EventTrigger RoutedEvent="MouseEnter"> 
     <BeginStoryboard> 
      <Storyboard> 
       <ColorAnimation To="Red" 
         Duration="0:0:2" 
         Storyboard.TargetName="QButton" 
         Storyboard.TargetProperty="(BGColor).(SolidColorBrush.Color)"/> 
      </Storyboard> 
     </BeginStoryboard> 
    </EventTrigger> 
</Button.Triggers>