如何与动态资源绑定并指定路径 [英] How to bind with dynamic resource and specifying a path
问题描述
我想绑定到资源(DynamicResource)并访问该资源的属性,但是有办法吗?
I want to bind to a resource (DynamicResource) and access properties on that resource, but is there a way to do that?
(我想在Visual Studio的xaml编辑器中可视化来自构造函数的默认值.当通过DataContext或通过我的Window类添加的属性引用对象时,无法看到这些默认值.)
(I want to visualize the default values from constructor in the xaml editor in visual studio. Those cannot be seen when referencing an object through DataContext nor through a property added on my Window class...)
无法使用xaml:(在composer中有效,但在运行时不起作用...)
Not working xaml: (works in composer but not at runtime...)
<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>
使用该类(可能需要实现INotifyPropertyChanged):
with the class (which probably need to implement INotifyPropertyChanged):
public class MyClass
{
public MyClass()
{
this.Property1 = "Ok";
this.Property2 = "Cancel";
}
public string Property1 { get; set; }
public string Property2 { get; set; }
}
推荐答案
这是因为DynamicResource
标记扩展名只能用于依赖项属性,因为如果资源发生更改,它将需要对其进行更新.而且Binding.Source
不是依赖项属性...
That's because the DynamicResource
markup extension can only be used on a dependency property, because it will need to update it if the resource changes. And Binding.Source
is not a dependency property...
作为解决方法,您可以使用DynamicResource
设置按钮的DataContext
:
As a workaround, you could set the DataContext
of the button with the DynamicResource
:
<Button DataContext="{DynamicResource myResource}" Content="{Binding Path=Property1}" />
<Button DataContext="{DynamicResource myResource}" Content="{Binding Path=Property2}" />
这篇关于如何与动态资源绑定并指定路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!