Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 为什么数据绑定到DynamicSource不起作用?_Wpf - Fatal编程技术网

Wpf 为什么数据绑定到DynamicSource不起作用?

Wpf 为什么数据绑定到DynamicSource不起作用?,wpf,Wpf,以下代码不起作用。我如何让它工作 <Image Source="{DynamicResource {Binding VM.ImageKey}}" /> 这是对的不正确使用。正确的答案是: <Image Source="{DynamicResource VM.ImageKey}" /> 假设您当前的DataContext是一个实例,它有一个名为VM的属性,该属性又有一个名为ImageKey的属性,该属性是的派生类型。如果要动态指定资源键,则应使用ResourceKey标

以下代码不起作用。我如何让它工作

<Image Source="{DynamicResource {Binding VM.ImageKey}}" />

这是对的不正确使用。正确的答案是:

<Image Source="{DynamicResource VM.ImageKey}" />

假设您当前的
DataContext
是一个实例,它有一个名为VM的属性,该属性又有一个名为ImageKey的属性,该属性是的派生类型。

如果要动态指定资源键,则应使用ResourceKey标记扩展指定它-不确定它是否以您希望的方式支持绑定然而。有关更多详细信息,请参阅。

此行为是设计的。绑定仅对依赖项对象的依赖项属性有效,而MarkupExtension不是依赖项对象。

它无法工作,因为动态资源是而不是。数据绑定仅适用于Dependency属性

然而,有一个半平滑的解决方法。创建一个DynamicTextBlock类,该类扩展了

xaml:

<TextBlock x:Class="Rebtel.Win.App.Controls.DynamicTextBlock"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"/>
用法:

  <local:DynamicTextBlock TextKey="{Binding TextKeyProperty}" />


TextKeyProperty然后返回可在ResourceDictionary中找到的键。图像及其源属性也可以采用相同的方法。

我假设在本例中,
VM.ImageKey
引用数据源上的属性,您希望将其值用作资源字典键。其思想是,您的数据源可以通过提供资源密钥来确定使用哪个映像。(本页上的大多数其他答案都没有帮助,因为它们不幸错过了您要做的事情,假设您想使用文本
“VM.ImageKey”
作为资源密钥,我很确定这不是您想要的。)


这似乎不受支持,但有另一种方法可以让您通过数据绑定确定的键来选择图像资源:

此外,如果ImageKey是VM类上的静态字段或属性,您可以使用{x:static}语法来检索它:其中lcl是为VM clr命名空间定义的xmlns。
<TextBlock x:Class="Rebtel.Win.App.Controls.DynamicTextBlock"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"/>
public partial class DynamicTextBlock : TextBlock
{
    public static readonly DependencyProperty TextKeyProperty = DependencyProperty.Register(
        "TextKey", typeof(string), typeof(DynamicTextBlock), new PropertyMetadata(string.Empty, OnTextKeyChanged));

    private static void OnTextKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var me = ((DynamicTextBlock)d);
        if (e.NewValue != null)
        {
            me.TextKey = (string) e.NewValue;
        }
    }

    public string TextKey
    {
        set { SetResourceReference(TextProperty, value); }
    }

    public DynamicTextBlock()
    {
        InitializeComponent();
    }
}
  <local:DynamicTextBlock TextKey="{Binding TextKeyProperty}" />