如何绑定动态资源并指定路径
我想绑定到资源 (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; }
}
I want to bind to a resource (DynamicResource) and access properties on that resource, but is there a way to do that?
(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...)
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>
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; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为
DynamicResource
标记扩展只能在依赖项属性上使用,因为如果资源发生更改,它将需要更新它。并且Binding.Source
不是依赖属性...作为解决方法,您可以使用
DynamicResource
设置按钮的DataContext
: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. AndBinding.Source
is not a dependency property...As a workaround, you could set the
DataContext
of the button with theDynamicResource
:滥用不相关对象的 DataContext 似乎是最简单的解决方法。
如果您仍然需要控件的 DataContext(MVVM 任何人?),您还可以在其他地方创建一个不可见的帮助程序 FrameworkElement:
然后通过使用绑定中的名称来引用它:
您的设计人员很可能会抱怨无法在“对象”的上下文中解析“颜色”,但它在运行时可以正常工作。
Abusing the DataContext of an unrelated object seems to be the easiest workaround.
In case you still need the DataContext of your control (MVVM anyone?), you can also create an invisible helper FrameworkElement elsewhere:
and later refer to it by using the name in the binding:
Your designer will quite likely complain about not being able to resolve "Color" in the context of "object", but it will work fine at runtime.