[英]WPF: XAML: Give DataContext a name without instantiating it
In my XAML I have a UserControl1
which I am trying to bind to the MainWindowViewModel
of MainWindow
: 在我的XAML中,我有一个UserControl1
,我试图将其绑定到MainWindowViewModel
的MainWindow
:
<ControlLib:UserControl1 Hotzenplotz="{Binding Raeuber, ElementName=vm}" />
Hotzenplotz
is a DependenyProperty
of UserControl1
. Hotzenplotz
是UserControl1
的DependenyProperty
。 Raeuber
is a property of MainWindowViewModel
. Raeuber
是MainWindowViewModel
的属性。
The catch is the ElementName=vm
because I don't want XAML to look up the property in UserControl1
but in my MainWindowViewModel
问题在于ElementName=vm
因为我不希望XAML在UserControl1
而是在MainWindowViewModel
查找该属性。
If I bind my MainWindowViewModel
like this everything is peachy: 如果我像这样绑定我的MainWindowViewModel
那么一切都会变得很桃花:
<Window.DataContext>
<local:MainWindowViewModel x:Name="vm" />
</Window.DataContext>
Unfortunately I can't instantiate MainWindowViewModel
on-the-fly, I need to bind it from the code side. 不幸的是,我无法即时实例化MainWindowViewModel
,我需要从代码端进行绑定。 But then I cannot figure out on how to give the DataContext
property the name vm
for future reference. 但是,然后我无法弄清楚如何为DataContext
属性赋予名称vm
以便将来参考。
Edit 编辑
I solved it this way. 我这样解决了。 I added a name to the MainWindow
我在MainWindow
添加了一个名称
<Window x:Name="mw"
And access the binding with the help of the DataContext
property 并借助DataContext
属性访问绑定
<ControlLib:UserControl1 Hotzenplotz="{Binding Path=DataContext.Raeuber, ElementName=mw}" />
But is this really the correct way? 但这真的是正确的方法吗?
Edit 2 编辑2
The working code is available here: http://doena-soft.de/tmp/SubControls.zip 可在此处找到工作代码: http : //doena-soft.de/tmp/SubControls.zip
OK, I found the solution here: Binding between my usercontrol and ViewModel 好的,我在这里找到了解决方案: 在usercontrol和ViewModel之间进行绑定
I had the UserControl1
bound to its own DataContext
like this: 我将UserControl1
绑定到了自己的DataContext
如下所示:
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Instead now I gave the UserControl1
inside its own XAML a name "uc" and referred all bindings there to this element name. 现在,我改为在其自己的XAML中为UserControl1
命名为“ uc”,并将那里的所有绑定都引用到该元素名称。
Inside UserControl1
before: 在UserControl1
之前:
<Label x:Name="label1" Content="{Binding Hotzenplotz}" />
And after 之后
<Label x:Name="label1" Content="{Binding Hotzenplotz, ElementName=uc}" />
For completeness' sake, here is the second solution: http://doena-soft.de/tmp/SubControls_better.zip 为了完整起见,这是第二种解决方案: http : //doena-soft.de/tmp/SubControls_better.zip
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.