如何与动态资源绑定并指定路径

eri*_*ikH 9 xaml binding dynamicresource visual-studio

我想绑定到资源(DynamicResource)并访问该资源上的属性,但有没有办法做到这一点?

(我想在visual studio的xaml编辑器中可视化构造函数的默认值.当通过DataContext引用对象或通过我的Window类中添加的属性时,无法看到这些值...)

不工作xaml :( 在作曲家工作,但不在运行时...)

<Window ... >
    <Window.Resources>
        <local:MyClass x:Key="myResource"  />
    </Window.Resources>
    <StackPanel>
        <Button Content="{Binding Source={DynamicResource myResource} Path=Property1}" />
        <Button Content="{Binding Source={DynamicResource myResource} Path=Property2}" />
    </StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)

与类(可能需要实现INotifyPropertyChanged):

public class MyClass 
{
    public MyClass()
    {
        this.Property1 = "Ok";
        this.Property2 = "Cancel";
    }
    public string Property1 { get; set; }
    public string Property2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*que 20

这是因为DynamicResource标记扩展只能用于依赖项属性,因为如果资源发生更改,它将需要更新它.而且Binding.Source不是依赖属性......

作为解决方法,您可以使用以下命令设置DataContext按钮DynamicResource:

<Button DataContext="{DynamicResource myResource}" Content="{Binding Path=Property1}" />
<Button DataContext="{DynamicResource myResource}" Content="{Binding Path=Property2}" />
Run Code Online (Sandbox Code Playgroud)