找不到ControlTemplate中定义的资源

时间:2013-09-13 11:53:15

标签: wpf xaml resources

我有一个带有我窗口样式的资源字典。在这种风格中,我定义了模板,并在其中定义了很多东西。除此之外,我定义了一个故事板来动画模板中定义的某些内容。它看起来像这样:

<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>

现在我有一个MyWindow的实例(确定应用样式:))并且在窗口内我想触发动画。但是,这个

this.FindResource("MyAnimation");

失败!

如果我在

中移动故事板
<ControlTemplate.Resources/>

它可以找到它,但如果我这样做

((Storyboard)FindResource("StoryboardOpenOverlay")).Begin();

我收到另一个错误,它无法找到ToBeAnimated ...

有什么想法吗?

2 个答案:

答案 0 :(得分:4)

您可以在网格上添加名称并使用模板化部分来获取它的引用,以便执行此操作:
- 在你的MyWindow班级上添加[TemplatePart(Name = "gridName",DataGrid.headerName, Type = typeof(Grid))] - 并实现OnApplyTemplate:

    protected override void OnApplyTemplate()
    {
        Grid grid = this.GetTemplateChild("gridName") as Grid;
        if (grid != null)
        {
            Storyboard storyboard = grid.Resources["MyAnimation"] as Storyboard ;

        }
        base.OnApplyTemplate();
    }

答案 1 :(得分:1)

虽然故事板放在Grid中,但请尝试以下操作:

((Grid)this.Content).FindResource("MyAnimation");

或者,如果可能的话,

this.ToBeAnimated.FindResource("MyAnimation");