wpf - 是否可以在多重绑定(bind)中使用动态资源?

标签 wpf multibinding markup-extensions dynamicresource

在本例中,我希望使用资源字典中声明的字符串作为 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>

我可以将指定资源文件中的string1string2注入(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 or FrameworkContentElement. That property must be backed by a DependencyProperty.
  • 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 a FrameworkElement or FrameworkContentElement property, or a Setter value.

Source: XAML Resources, MSDN .

因此,如果使用Binding,则所有语句都会被违反。

如图所示,DynamicResourceExtension 对于 Run 类的实例工作得很好,因为 Run 类(至少)是派生的来自 FrameworkContentElement 类。

其他引用

  1. 资源部分:Wha' Happened Part Two: More Property Changes in WPF .
  2. WPF: Dependency Properties & Resources .

关于wpf - 是否可以在多重绑定(bind)中使用动态资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16962827/

相关文章:

使用 Caliburn.Micro 实现 WPF UI 自动化?

wpf - 在 WPF 样式中设置嵌套元素的属性

WPF 性能加载用户控件

wpf - 如何调试 Visual Studio 2012 实例设计时

c# - 使用转换器创建标记扩展

c# - 分页后 TableCell 拆分 : remainder split part loses original cell properties

c# - 无法使用多重绑定(bind)绑定(bind) DataGrid ItemsSource - 简单绑定(bind)工作正常

c# - 多重绑定(bind)生成 "Cannot set MultiBinding because MultiValueConverter must be specified"

c# - 如何在此多绑定(bind)示例中设置源?

c# - 改进的 IValueConverter——MarkupExtension 还是 DependencyObject?