问题
I have a resource dictionary with a style for my window. In this style i define the template and inthere i define a lot of stuff. Among others i define a storyboard to animate certain things that are defined in the template. It look something like this:
<Style TargetType="local:MyWindow">
<Setter Property="Background" Value="red" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyWindow">
<Grid>
<Grid.Resources>
<Storyboard x:Key="MyAnimation">
<DoubleAnimation Storyboard.TargetName="ToBeAnimated" ... />
</Storyboard>
</Grid.Resources>
<Grid x:Name="ToBeAnimated" Background="Green"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Now i have an instance of MyWindow (which definitly applys the style :) ) and from within the window i want to trigger the animation. However, this
this.FindResource("MyAnimation");
fails!
If i move the storyboard in the
<ControlTemplate.Resources/>
it can find it, but if i do
((Storyboard)FindResource("StoryboardOpenOverlay")).Begin();
i get another error that it cannot find the ToBeAnimated
...
Any ideas?
回答1:
You can add a name on the Grid and use templated part to get a reference on it, to do that:
-Add [TemplatePart(Name = "gridName",DataGrid.headerName, Type = typeof(Grid))]
on you MyWindow class
-And implement OnApplyTemplate:
protected override void OnApplyTemplate()
{
Grid grid = this.GetTemplateChild("gridName") as Grid;
if (grid != null)
{
Storyboard storyboard = grid.Resources["MyAnimation"] as Storyboard ;
}
base.OnApplyTemplate();
}
回答2:
Though the storyboard is placed in your Grid
, try this:
((Grid)this.Content).FindResource("MyAnimation");
or, if it is possible,
this.ToBeAnimated.FindResource("MyAnimation");
来源:https://stackoverflow.com/questions/18785671/cannot-find-resource-that-is-defined-in-controltemplate