我在名为“Error”的Style中创建了一个状态,并在故事板中附加了动画。
我希望能够在满足特定条件的情况下从使用该Style的Control启动该动画。
例如,当我的View的DataContext中的属性设置为某个值时。
我究竟如何启动控件样式中定义的故事板?
答案 0 :(得分:2)
在控件后面的代码中执行
Storyboard myStoryboard = this.FindResource("NameOfMyStoryBoard") as Storyboard;
if(myStoryboard != null)
{
myStoryboard.Begin();
}
如果您的故事板未设置为资源但嵌入在您的样式中,请将其声明为资源并以您的样式引用它。
MSDN文档:Storyboard
答案 1 :(得分:1)
以下是使用触发器从XAML执行此操作的方法:
<Style TargetType="Button" x:Key="MyStyle">
<Style.Resources>
<Storyboard x:Key="MyGetFocusAnimation">
<DoubleAnimation Storyboard.TargetProperty="Height"
To="50"
Duration="0:0:.3" />
</Storyboard>
<Storyboard x:Key="MyLoseFocusAnimation">
<DoubleAnimation Storyboard.TargetProperty="Height"
To="30"
Duration="0:0:.3" />
</Storyboard>
</Style.Resources>
<Style.Triggers>
<Trigger Property="IsMouseOver"
Value="True">
<Trigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource MyGetFocusAnimation}" />
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard Storyboard="{StaticResource MyLoseFocusAnimation}" />
</Trigger.ExitActions>
</Trigger>
<Trigger Property="IsKeyboardFocusWithin"
Value="True">
<Trigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource MyGetFocusAnimation}" />
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard Storyboard="{StaticResource MyLoseFocusAnimation}" />
</Trigger.ExitActions>
</Trigger>
</Style.Triggers>
</Style>
在定义上面的样式后,您只需告诉按钮使用哪种样式:
<Button Content="Content" Height="20" Width="100" Style="{StaticResource MyStyle}"/>
答案 2 :(得分:1)
我最终创建了一个可以容纳我所有控件的课程。验证依赖属性:
public class ValidationProperties
{
#region IsValid Dependency Property
/// <summary>
/// An attached dependency property which provides an
/// </summary>
public static readonly DependencyProperty IsValidProperty;
/// <summary>
/// Gets the <see cref="IsValidProperty"/> for a given
/// <see cref="DependencyObject"/>, which provides an
/// </summary>
public static bool GetIsValid(DependencyObject obj)
{
return (bool)obj.GetValue(IsValidProperty);
}
/// <summary>
/// Sets the attached <see cref="IsValidProperty"/> for a given
/// <see cref="DependencyObject"/>, which provides an
/// </summary>
public static void SetIsValid(DependencyObject obj, bool value)
{
obj.SetValue(IsValidProperty, value);
}
#endregion IsValid Dependency Property
static ValidationProperties()
{
// Register attached dependency property
IsValidProperty = DependencyProperty.RegisterAttached("IsValid",
typeof(bool),
typeof(ValidationProperties),
new FrameworkPropertyMetadata(true));
}
}
在此之后,我修改了样式以启动动画,具体取决于使用该样式的控件的属性值:
(...)
<Trigger Property="AttachedProperties:ValidationProperties.IsValid" Value="false">
<Trigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource ControlIsInvalid}"/>
</Trigger.EnterActions>
</Trigger>
(...)
我最终将Control上的Dependency属性绑定到模型中的值(通过View-Model):
<TextBox x:Name="UsernameTextbox"
(...)
AttachedProperties:ValidationProperties.IsValid="{Binding SessionHandler.SessionUser.UsernameIsValid}"/>