[英]Binding resource property to DataContext property
I was wondering if I could have a child window model in main window resource section and have its properties bound to main model. 我想知道是否可以在主窗口资源部分中有一个子窗口模型,并将其属性绑定到主模型。 I have a simple string property on first model and string
DependencyProperty
on second and tried to bind this way: 我在第一个模型上有一个简单的字符串属性,在第二个模型上有一个字符串
DependencyProperty
,并尝试通过这种方式进行绑定:
<Window.DataContext>
<local:MainWindowModel x:Name="MainWindowModel"/>
</Window.DataContext>
<Window.Resources>
<local:SecondWindowModel x:Key="SecondWindowModel" SecondString="{Binding FirstString}"/>
</Window.Resources>
SecondWindowModel
is a DependencyObject
and SecondString
is a DependencyProperty
as WPF requires. SecondWindowModel
是一个DependencyObject
和SecondString
是一个DependencyProperty
作为WPF需要。 But SecondString
is always null, its setter is never called. 但是
SecondString
始终为null,从不调用其setter。 Why? 为什么?
My guess would be that WPF will instanciate the MainWindowModel viewmodel correctly as the Window's DataContext. 我的猜测是WPF将正确地实例化MainWindowModel视图模型作为Window的DataContext。
But your SecondWindowModel viewmodel being a resource, is actually a static resource .
但是您的SecondWindowModel视图模型是一种资源,实际上是一种静态资源 。
And in C# a static class is initialized only when you first use it. 并且在C#中,仅在您第一次使用静态类时才对其进行初始化。 I'm not sure if WPF initializes its static resources upon declaration.
我不确定WPF是否在声明时初始化其静态资源。
You can add a static constructor to SecondWindowModel with a break point and check if it is actually initialized before MainWindowViewModel or not at all. 您可以向带有中断点的SecondWindowModel中添加静态构造函数,并检查它是否实际上在MainWindowViewModel之前进行了初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.