【发布时间】:2011-09-28 11:19:57
【问题描述】:
刚开始使用 WPF / MVVM 并且有一个关于使用视图模型作为 wpf 窗口的数据上下文的问题。
我使用的是视图优先方法,我的视图看起来像这样;
<Window x:Class="TestContext.TestForm"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TestForm" Height="300" Width="300"
DataContext="{StaticResource testViewModel}">
<Grid>
<TextBox Text="{Binding Path=Address}" Height="23" HorizontalAlignment="Left" Margin="34,44,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
</Grid>
</Window>
然后我用这样的代码创建我的视图模型;
public class ViewModelFactory
{
public TestViewModel CreateTestViewModel()
{
return new TestViewModel();
}
}
每当我实例化视图时,我都会在 app.xaml 中使用以下方法来创建视图模型的实例;
<ObjectDataProvider x:Key="testViewModel" ObjectInstance="{StaticResource viewModelFactory}" MethodName="CreateTestViewModel">
这一切都很好。
问题是我只看到创建了一次视图模型。因此视图的新实例使用相同的视图模型实例。
我想从视图模型的新实例开始。
如果我在表单构造器中手动创建视图模型;
public TestForm()
{
InitializeComponent();
this.DataContext = new TestViewModel();
}
然后它按预期工作。
我正试图弄清楚这里发生了什么......
谢谢....
【问题讨论】:
-
您是如何添加新视图的?使用方法绑定的技巧是指定一些使用绑定的方法参数,然后通过更改绑定到参数的底层属性,您可以触发方法调用,我不知道触发方法调用的其他方式(我也很感兴趣如果存在这种方式)
标签: wpf mvvm datacontext