由于 Windows 运行时 XAML 实现的现有限制,您无法对自定义附加属性进行动画处理。请参见动画 XAML 附加属性部分在MSDN文档.
对于您的情况,您可以创建自定义用户控件并为此用户控件定义依赖项属性。然后,您可以为该依赖属性设置动画。
在此属性的 PropertyChangedCallback 处理程序方法中,您可以更改 ScrollViewer 的 Horizontalofset。
详细请参考我下面的代码示例:
<UserControl
x:Class="Appanimate.MyUserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Appanimate"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid>
<ScrollViewer x:Name="scrolviewer" Width="200" Height="100" HorizontalScrollBarVisibility="Visible">
<TextBlock Text="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" FontSize="20"/>
</ScrollViewer>
</Grid>
public sealed partial class MyUserControl1 : UserControl
{
public MyUserControl1()
{
this.InitializeComponent();
}
public double Horizontalofset
{
get { return (double)GetValue(HorizontalofsetProperty); }
set { SetValue(HorizontalofsetProperty, value); }
}
// Using a DependencyProperty as the backing store for Horizontalofset. This enables animation, styling, binding, etc...
public static readonly DependencyProperty HorizontalofsetProperty =
DependencyProperty.Register("Horizontalofset", typeof(double), typeof(MyUserControl1), new PropertyMetadata(0,PropertyChangedCallback));
public static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var distance = (d as MyUserControl1).scrolviewer.ScrollableWidth;
if (distance > (double)e.NewValue)
{
var ret = (d as MyUserControl1).scrolviewer.ChangeView((double)e.NewValue, (d as MyUserControl1).scrolviewer.VerticalOffset, (d as MyUserControl1).scrolviewer.ZoomFactor);
Debug.WriteLine(ret);
}
}
}
<Grid x:Name="maingrid" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.Resources>
<Storyboard x:Key="animation" x:Name="animation">
<DoubleAnimation Storyboard.TargetName="myusercontrol"
Storyboard.TargetProperty="Horizontalofset"
Duration="0:0:1" From="0" To="80" EnableDependentAnimation="True"/>
</Storyboard>
</Grid.Resources>
<Button Width="100" Height="50" Click="Button_Click"/>
<local:MyUserControl1 x:Name="myusercontrol" Horizontalofset="0"></local:MyUserControl1>
</Grid>
private void Button_Click(object sender, RoutedEventArgs e)
{
animation.Begin();
}
请注意,您需要启用EnableDependentAnimation
,如果没有,你的动画将无法工作。