以编程方式访问Silverlight静态资源

Tri*_*ion 11 silverlight xaml

我想以编程方式访问静态资源,就像在XAML中一样:

<TextBlock Text="{Binding Source={StaticResource My.Text.Key}}" />
Run Code Online (Sandbox Code Playgroud)

无论我的静态资源是在TextBlock,某些父元素(例如UserControl)甚至应用程序上定义的,这都有效.似乎StaticResource绑定表达式知道如何向上走元素树,或者元素本身如何.我想以编程方式执行相同的操作:

<UserControl x:Class="MyCustomControl" ...>
    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources.xaml"/> <!-- Sets 'My.Text.Key' to System.String 'Hello, World!' -->
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>
</UserControl>

public partial class MyCustomControl
{
    public MyCustomControl()
    {
        InitializeComponent();
        string myCustomValue = this.Resources[MyCustomValue] as string; // myCustomValue becomes null!
    }
}
Run Code Online (Sandbox Code Playgroud)

即使在这个简单的测试中,我的资源似乎无法以编程方式访问.这是我尝试真正做的简化版本:通过附加自定义动态属性的元素找到静态资源(例如uiElement.Resources [key]).

Ant*_*nes 17

尽管你的评论相反,我怀疑使用"." 在您的资源键中确实是您的问题的根源.在这种情况下"." 没有特殊意义,也不会影响资源的访问方式.(我已尝试过但未能重现任何问题).

虽然使用{StaticResource MyName}标记扩展和尝试以编程方式查找资源之间存在很大差异.

标记扩展导致XamlParser寻找指定键的Resources财产FrameworkElement的财产被分配属于.如果找不到密钥,它会在父级中查找它,FrameworkElement并且一直到达根目录FrameworkElement.如果仍未找到它,请查看Application的Resources属性.

另一方面,这段代码: -

string myCustomValue = this.Resources[MyCustomValue] as string;
Run Code Online (Sandbox Code Playgroud)

sf只是查看用户控件的单个Resources属性.没有尝试在祖先或应用程序资源中搜索密钥.它是一个简单的字典查找.我怀疑这是真正绊倒你的.

话虽如此,我会说使用"." 在资源键中可能不是一个好主意."." 在各种XAML场景中确实有意义,因此在键名中使用它也有可能混淆开发人员阅读代码,即使Silverlight对此非常满意.