Cannot find resource that is defined in ControlTemplate

此生再无相见时 提交于 2020-01-03 19:09:51

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!