在本例中,我希望使用资源字典中声明的字符串作为 Text
属性绑定(bind)的一部分。仅绑定(bind)单个动态资源字符串不是问题:
<TextBlock Text="{DynamicResource keyToMyString}" />
但是,如果您需要使用StringFormat,您很快就会遇到问题。在MultiBinding上因为您需要插入动态文本或想要组合多个字符串。例如,如果我的 MultiBinding 如下所示:
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} {1} some more text">
<Binding Source="{x:Static Resources:Strings.string1}" />
<Binding Source="{x:Static Resources:Strings.string2}" />
</MultiBinding>
<TextBlock.Text>
我可以将指定资源文件中的string1
和string2
注入(inject)到绑定(bind)文本中,没有任何问题。但我找不到以同样的方式使用动态资源中的字符串的方法。 (我使用此方法将公司和产品名称注入(inject)合并资源字典中的文本中)。
带有TextBlock我可以通过使用几个 Run 来规避这个问题TextBlock 内容的项目 ( reference ):
<TextBlock >
<Run Text="{DynamicResource CompanyName}" />
<Run Text="{DynamicResource ProductName}" />
<Run Text="{DynamicResource MajorVersion}" />
</TextBlock>
但是当需要将动态资源绑定(bind)到 Window Title 时,这没有任何帮助。属性(property)。无论如何,是否可以通过(如有必要,创造性地)使用现有的标记扩展(例如 x:Static
等)来实现此目的?或者我们是否必须编写自己的标记扩展来实现此目的?
最佳答案
Dynamic resource references have some notable restrictions. At least one of the following must be true:
- The property being set must be a property on a
FrameworkElement
orFrameworkContentElement
. That property must be backed by aDependencyProperty
.- The reference is for a value within a
Style
Setter
.- The property being set must be a property on a
Freezable
that is provided as a value of either aFrameworkElement
orFrameworkContentElement
property, or aSetter
value.
Source: XAML Resources, MSDN .
因此,如果使用Binding
,则所有语句都会被违反。
如图所示,DynamicResourceExtension
对于 Run
类的实例工作得很好,因为 Run
类(至少)是派生的来自 FrameworkContentElement
类。
其他引用
关于wpf - 是否可以在多重绑定(bind)中使用动态资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16962827/