與@ Novitchi的答案類似,我還想創建一個具有附加屬性的行爲。但我會的行爲附加到mouse click
:
所以,你可以創建自己的行爲如下:
public static class BlinkingBehaviour
{
public static bool GetIsBlinkingWhenClick(UIElement element)
{
return (bool)element.GetValue(IsBlinkingWhenClickProperty);
}
public static void SetIsBlinkingWhenClick(UIElement element, bool value)
{
element.SetValue(IsBlinkingWhenClickProperty, value);
}
public static readonly DependencyProperty IsBlinkingWhenClickProperty =
DependencyProperty.RegisterAttached(
"IsBlinkingWhenClick",
typeof(bool),
typeof(BlinkingBehaviour),
new FrameworkPropertyMetadata(false, OnIsBlinkingWhenClickChanged));
static void OnIsBlinkingWhenClickChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if ((bool)e.NewValue)
{
(d as UIElement).PreviewMouseLeftButtonDown -= BlinkingWhenClickBehavior_PreviewMouseLeftButtonDown;
(d as UIElement).PreviewMouseLeftButtonDown += BlinkingWhenClickBehavior_PreviewMouseLeftButtonDown;
}
else
{
(d as UIElement).PreviewMouseLeftButtonDown -= BlinkingWhenClickBehavior_PreviewMouseLeftButtonDown;
}
}
static void BlinkingWhenClickBehavior_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DoubleAnimation blink = new DoubleAnimation() {
To = 1,
From = 0,
Duration = TimeSpan.FromMilliseconds(200) };
(sender as UIElement).BeginAnimation(UIElement.OpacityProperty, blink);
}
}
然後在您的XAML,你可以將它連接到您的image
:
<Window x:Class="YourNameSpace.YourWindowClass"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:YourNameSpace"
<Button ...>
<Image local:BlinkingBehaviour.IsBlinkingWhenClick="True" .../>
</Button>
</Window>
我將你設置爲解決方案,因爲我在這篇文章後做了同樣的事情:https://programmingistheway.wordpress.com/2015/06/24/mvvm-and-wpf-blink-an-image-from-view-model/ –