Reputation: 36866
I have a Grid inside of an ItemsControl's DataTemplate, so there will be many copies of this grid. I want a mouse click on the grid to trigger the storyboard of an element outside of the DataTemplate. For example, I would like to animate Transform properties of a named element that exists elsewhere in the Window.
Let's say my DataTemplate looks something like this:
<DataTemplate x:Key="myDataTemplate">
<Grid>
<Grid.Triggers>
<EventTrigger RoutedEvent="UIElement.MouseLeftButtonUp">
<BeginStoryboard>
<Storyboard Storyboard.TargetName="myRectangle">
<DoubleAnimation Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[1].(TranslateTransform.X)"
To="10" Duration="0:0:0.2" />
<DoubleAnimation Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[1].(TranslateTransform.Y)"
To="10" Duration="0:0:0.2" />
<DoubleAnimation Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)"
To="1" Duration="0:0:0.5" />
<DoubleAnimation Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"
BeginTime="0:0:0.5" To="1" Duration="0:0:0.5" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Grid.Triggers>
</Grid>
</DataTemplate>
and somewhere in my window I have a Rectangle that looks like this:
<Rectangle x:Name="myRectangle" Height="400" Width="400">
<Rectangle.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="0" ScaleY="0" />
<TranslateTransform />
</TransformGroup>
</Rectangle.RenderTransform>
</Rectangle>
When the MouseLeftButtonUp event fires, I get the following exception:
'myRectangle' name cannot be found in the name scope of 'System.Windows.Controls.Grid'.
Is there a way to tell the storyboard where to look for an element by this name? I'm especially interested in a xaml-only solution if one exists.
Upvotes: 3
Views: 3513
Reputation: 4354
It's possible to find xaml elements in a different namescope (i.e. external of the data template) by using the FindAncestor mode of a RelativeSource binding, as long as the xaml element you're trying to bind to is a parent element. The binding code would look like:
{Binding Path="myRectangle", RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Rectangle}}}
Name bindings in storyboards may be a different animal entirely, but perhaps you can use this.
Upvotes: 1