I have created an attached dependency property for Storyboards, with the intention of enabling me to call a method on my ViewModel when a Storyboard Completed event fires:
public static class StoryboardExtensions
{
public static ICommand GetCompletedCommand(DependencyObject target)
{
return (ICommand)target.GetValue(CompletedCommandProperty);
}
public static void SetCompletedCommand(DependencyObject target, ICommand value)
{
target.SetValue(CompletedCommandProperty, value);
}
public static readonly DependencyProperty CompletedCommandProperty =
DependencyProperty.RegisterAttached(
"CompletedCommand",
typeof(ICommand),
typeof(StoryboardExtensions),
new FrameworkPropertyMetadata(null, OnCompletedCommandChanged));
static void OnCompletedCommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
Storyboard storyboard = target as Storyboard;
if (storyboard == null) throw new InvalidOperationException("This behavior can be attached to Storyboard item only.");
storyboard.Completed += new EventHandler(OnStoryboardCompleted);
}
static void OnStoryboardCompleted(object sender, EventArgs e)
{
Storyboard item = ... // snip
ICommand command = GetCompletedCommand(item);
command.Execute(null);
}
}
then I try to use it in XAML, with a Binding syntax:
<Grid>
<Grid.Resources>
<Storyboard x:Key="myStoryboard" my:StoryboardExtensions.CompletedCommand="{Binding AnimationCompleted}">
<DoubleAnimation Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:5" />
</Storyboard>
<Style x:Key="myStyle" TargetType="{x:Type Label}">
<Style.Triggers>
<DataTrigger
Binding="{Binding Path=QuestionState}" Value="Correct">
<DataTrigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource myStoryboard}" />
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<Label x:Name="labelHello" Grid.Row="0" Style="{StaticResource myStyle}">Hello</Label>
</Grid>
This fails with the following exception:
System.Windows.Markup.XamlParseException occurred Message="Cannot convert the value in attribute 'Style' to object of type 'System.Windows.Style'. Cannot freeze this Storyboard timeline tree for use across threads. Error at object 'labelHello' in markup file 'TestWpfApp;component/window1.xaml'
Is there any way to get the Binding syntax working with an attached ICommand property for a Storyboard?