【问题标题】:How does a behavior have access to the resource hierarchy of the associated element?行为如何访问关联元素的资源层次结构?
【发布时间】:2015-11-19 10:27:01
【问题描述】:

今晚在解决动态资源问题时,我最终找到了一个解决方案,它依赖于Behavior 类参与其相关框架元素的资源层次结构的能力。例如,考虑以下

<Application>
    <Application.Resources>
        <system:String x:Key="TestString">In App Resources</system:String>
    </Application.Resources>

</Application>
<Window>
    <Window.Resources>
        <system:String x:Key="TestString">In Window Resources/system:String>
    </Window.Resources>

    <Border>
       <Border.Resources>
            <system:String x:Key="TestString">In Border Resources</system:String>
       </Border.Resources>

       <TextBlock Text="{DynamicResource TestString}" />

    </Border>

</Window>

TextBlock 将从边框显示资源。但是,如果我这样做...

public void Test()
{
    var frameworkElement = new FrameworkElement();
    var testString = (string)frameworkElement.FindResource("TestString");
}

...它从应用程序中找到一个,因为它不是可视化树的一部分。

也就是说,如果我改为这样做......

public class MyBehavior : Behavior<FrameworkElement>
{
    public string Value... // Implement this as a DependencyProperty
}

然后像这样添加到TextBlock中...

<TextBlock Text="{DynamicResource TestString}">
    <i:Interaction.Behaviors>
        <local:MyBehavior Value="{DynamicResource TestString}" />
    </i:Interaction.Behaviors>
</TextBlock>

行为确实获取资源的价值并将动态跟踪它。但是怎么做呢?

行为不是 FrameworkElement,因此您不能对其调用 SetResourceReference,它也不是可视树的一部分,因此即使您可以调用 SetResourceReference,它仍然无法找到 FrameworkElement 本地的资源。然而,这正是 Behavior 所做的。怎么样?

换一种说法,如果我们想编写自己的类来展示同样的行为(不是双关语),如何将自己插入到可视化树的资源层次结构中?

【问题讨论】:

    标签: c# wpf behavior resourcedictionary dynamicresource


    【解决方案1】:

    嗯,我想我找到了!秘密是可冻结的。简单地说,当您将 Freezable 添加到 FrameworkElement 的资源时,该 Freezable 上分配了 DynamicResource 的任何 DependencyProperties 都将正确解析。

    利用这些知识,我创建了一个 DynamicResourceBinding,让您可以像使用任何其他 DynamicResource 一样使用它,但还具有能够指定转换器、格式字符串等的额外优势。

    这是 StackOverflow 上该页面的链接,我对动态和静态资源都执行此操作...

    Post 33816511: How to create a DynamicResourceBinding

    【讨论】:

      猜你喜欢
      • 2012-08-04
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      相关资源
      最近更新 更多