本文主要记录Wpf各种控件的使用及自定义、动画等。
ContentControl添加自定义动画
有两种比较简易的方式,一是继承ContentControl
定义新控件,这个很明显是可行的,并且可以实现更复杂的需求,二是直接使用附加属性
给ContentControl
附加功能。
这里记录下第二种方式,主要是需求比较简单,后面用到再记录第一种方式。
直接新建一个ContentControlHelper
类,内容如下。
原理为
using System;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Windows;
namespace Yozily.UI.Wpf.Helpers
{
public static class ContentControlHelper
{
public static readonly DependencyProperty ContentChangedAnimationProperty = DependencyProperty.RegisterAttached(
"ContentChangedAnimation", typeof(Storyboard), typeof(ContentControlHelper), new PropertyMetadata(default(Storyboard), ContentChangedAnimationPropertyChangedCallback));
public static void SetContentChangedAnimation(DependencyObject element, Storyboard value)
{
element.SetValue(ContentChangedAnimationProperty, value);
}
public static Storyboard GetContentChangedAnimation(DependencyObject element)
{
return (Storyboard)element.GetValue(ContentChangedAnimationProperty);
}
private static void ContentChangedAnimationPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var contentControl = dependencyObject as ContentControl;
if (contentControl == null)
throw new Exception("Can only be applied to a ContentControl");
var propertyDescriptor = DependencyPropertyDescriptor.FromProperty(ContentControl.ContentProperty,
typeof(ContentControl));
propertyDescriptor.RemoveValueChanged(contentControl, ContentChangedHandler);
propertyDescriptor.AddValueChanged(contentControl, ContentChangedHandler);
}
private static void ContentChangedHandler(object sender, EventArgs eventArgs)
{
var animateObject = (FrameworkElement)sender;
var storyboard = GetContentChangedAnimation(animateObject);
storyboard.Begin(animateObject);
}
}
}
使用也比较简单,下面是给页面切换一个右侧淡入的效果。
<ContentControl x:Name="ActiveItem"
Grid.Column="1"
Grid.Row="1">
<ContentControl.RenderTransform>
<TranslateTransform />
</ContentControl.RenderTransform>
<helpers:ContentControlHelper.ContentChangedAnimation>
<Storyboard>
<DoubleAnimation Duration="0:0:0.3"
Storyboard.TargetProperty="(RenderTransform).X"
From="100">
<DoubleAnimation.EasingFunction>
<QuinticEase />
</DoubleAnimation.EasingFunction>
</DoubleAnimation>
<DoubleAnimation Duration="0:0:0.5" Storyboard.TargetProperty="Opacity" From="0" To="1" />
</Storyboard>
</helpers:ContentControlHelper.ContentChangedAnimation>
</ContentControl>
标签:控件,Storyboard,ContentControl,System,static,using,Wpf,定制
From: https://www.cnblogs.com/tincker/p/17142736.html