简体   繁体   English

如何以编程方式获取动态资源密钥名称?

[英]How to get a dynamic resource key name programmatically?

My program loads at runtime XAML file with following declaration of WPF control. 我的程序在运行时XAML文件中加载以下WPF控件声明。 The XamlReader.Load(...) method is used. 使用XamlReader.Load(...)方法。

<TextBlock Name="txMy" Text="{DynamicResource ResourceKey=MyTextFromRes}"/>

It works perfect and shows text from dynamic dictionary correctly. 它可以完美工作并正确显示动态词典中的文本。 Now I need to know NAME of KEY that resource dictionary at runtime because XAML file can be various. 现在,我需要在运行时知道该资源字典的KEY的名称,因为XAML文件可以多种多样。 I need to play with related dictionary values. 我需要使用相关的字典值。

How can I get a string with name of resource key (" MyTextFromRes " in this sample) at runtime in c# code? 如何在运行时以C#代码获取带有资源键名称的字符串(此示例中为“ MyTextFromRes ”)?

Create the following helper method: 创建以下帮助程序方法:

public string GetDynamicResourceKey(DependencyObject dObj, DependencyProperty dp)
{
    var value = dObj.ReadLocalValue(dp);
    var converter = new ResourceReferenceExpressionConverter();
    var dynamicResource = converter.ConvertTo(value, typeof(MarkupExtension)) as DynamicResourceExtension;
    return dynamicResource?.ResourceKey as string;
}

Now, use it with your TextBlock : 现在,将其与TextBlock一起使用:

var resourceKey = GetDynamicResourceKey(txMy, TextBlock.TextProperty);

I adapted this solution from here . 我从这里改编了这个解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM