【发布时间】:2015-09-16 06:19:54
【问题描述】:
我有一个子用户控件 (Page1),当它在 XAML 中声明为内联时,它未能继承在我的 WPF 窗口的 DataContext 上设置的 ViewModel (WizardPageViewModel):
<Window x:Class="WPFToolkitWizard.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:common="clr-namespace:WPFToolkitWizard"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<common:WizardPageViewModel/>
</Window.DataContext>
<Grid>
<common:MyWizardControl>
<common:MyWizardControl.Pages>
<common:Page1 Title="Page 1" Description="First page" IsValid="true" />
</common:MyWizardControl.Pages>
</common:MyWizardControl>
</Grid>
但是,如果我将其更改为静态资源并按如下方式引用它:
<Window.Resources>
<common:WizardPageViewModel x:Key="vm" />
</Window.Resources>
<common:Page1 Title="Page 1" Description="First page" IsValid="true" DataContext="{StaticResource vm}" />
在 Page1 中声明的依赖于注入的 VM 的绑定工作正常。问题是我想从 Window 的 DataContext 属性中引用 ViewModel,因为这是我们在整个团队中声明我们的 VM 的方式:
<Window.DataContext>
<common:WizardPageViewModel/>
</Window.DataContext>
我尝试如下设置绑定,但没有这样的运气:
<common:Page1 Title="Page 1" Description="First page" IsValid="true" DataContext="{Binding}" />
我也读过关于自动继承 DataContext 的帖子,但在这种情况下它不起作用。
查看详细的调试输出如下:
System.Windows.Data Warning: 60 : BindingExpression (hash=26218178): Default mode resolved to TwoWay
System.Windows.Data Warning: 61 : BindingExpression (hash=26218178): Default update trigger resolved to LostFocus
System.Windows.Data Warning: 62 : BindingExpression (hash=26218178): Attach to System.Windows.Controls.TextBox.Text (hash=35377412)
System.Windows.Data Warning: 67 : BindingExpression (hash=26218178): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=26218178): Found data context element: TextBox (hash=35377412) (OK)
System.Windows.Data Warning: 71 : BindingExpression (hash=26218178): DataContext is null
System.Windows.Data Warning: 65 : BindingExpression (hash=26218178): Resolve source deferred
它声明 DataContext 为空,但我只是不知道为什么它不能自动找到我的 VM 实例。
MyWizardControl 是一个用户控件
Page1 是一个 ContentControl
【问题讨论】:
-
我知道您正在尝试寻找解决方法,但要小心将您的虚拟机用作静态资源。所有资源(静态和动态)都是共享实例,因此绑定到该资源的任何其他内容都将被赋予与本示例中的 Window 相同的实例。如果您无法使其正常工作,请确保将 x:Shared 设置为 false。
标签: wpf xaml mvvm binding datacontext