我想绑定到资源(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>
与类(可能需要实现INotifyPropertyChanged):
public class MyClass
{
public MyClass()
{
this.Property1 = "Ok";
this.Property2 = "Cancel";
}
public string Property1 { get; set; }
public string Property2 { get; set; }
}
答案 0 :(得分:20)
这是因为DynamicResource
标记扩展只能用于依赖项属性,因为如果资源发生更改,它将需要更新它。并且Binding.Source
不是依赖属性...
作为解决方法,您可以使用DataContext
设置按钮的DynamicResource
:
<Button DataContext="{DynamicResource myResource}" Content="{Binding Path=Property1}" />
<Button DataContext="{DynamicResource myResource}" Content="{Binding Path=Property2}" />
答案 1 :(得分:0)
滥用不相关对象的DataContext似乎是最简单的解决方法。 如果您仍然需要控件的DataContext(任何人都需要MVVM?),还可以在其他位置创建不可见的帮助程序FrameworkElement:
<FrameworkElement Visibility="Collapsed" x:Name="ControlBrushGetter" DataContext="
{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />
,然后通过使用绑定中的名称来引用它:
<SolidColorBrush Opacity="0.8"
Color="{Binding ElementName=ControlBrushGetter, Path=DataContext.Color}" />
您的设计人员很可能会抱怨无法在“对象”的上下文中解析“颜色”,但是在运行时它将正常工作。