【问题标题】:Cannot find resource that is defined in ControlTemplate找不到在 ControlTemplate 中定义的资源
【发布时间】:2013-09-13 20:24:14
【问题描述】:

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

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

有什么想法吗?

【问题讨论】:

    标签: wpf xaml resources


    【解决方案1】:

    您可以在网格上添加一个名称并使用模板化部分来获取它的参考,以做到这一点:
    -在你的 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();
        }
    

    【讨论】:

    • 太棒了!谢谢。实际上,我可以随时调用 this.GetTemplateChild(...),而不仅仅是在 OnApplyTemplate() 中。谢谢!
    • 我更喜欢在 ApplyTemplate 中执行并将值保存在本地字段中,这样可以节省每次调用 GetTemplateChild 的成本
    【解决方案2】:

    虽然故事板放在您的Grid 中,但试试这个:

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

    或者,如果可能的话,

    this.ToBeAnimated.FindResource("MyAnimation");
    

    【讨论】:

    • 不要认为这行得通,this.Content 将是 ContentTemplate 而不是 ControlTemplate 中的任何内容,并且您不能 this.ToBeAnimated 使用,因为它是在样式中定义的
    • this.Content 是网格,因为故事板位于那里,所以它应该可以工作。
    • 不,this.Content 可能是一个网格,但不是 ControlTemplate 内的网格,它将是 ContentTemplate 内的任何内容。 (如果已定义,则内容显示在 ContentPresenter 内,而不是直接在 ControlTemplate 级别)
    • 就像定义了当前样式一样,没有 ContentPresenter 因此内容甚至不会显示(或者 MyWindows 甚至可能不是 ContentControl...)
    猜你喜欢
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 2011-02-17
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多