【问题标题】:Using ViewModel as WPF DataContext Disposing problems使用 ViewModel 作为 WPF DataContext 处理问题
【发布时间】: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


【解决方案1】:

诚实地使用ObjectDataProvider 并不是获取视图模型的好主意,因为该实例在App 中是单个的。

但如果您坚持重新创建视图模型,您将不得不刷新testViewModel

你这样做的方式是testViewModel.Refresh();

【讨论】:

    【解决方案2】:

    在代码中

    1. 创建您的视图
    2. 在视图上创建单个属性(称为 VM)
    3. 创建您的视图模型
    4. 将新视图模型分配给 VM
    5. 将 DataContext 设置为 ViewModel
    6. 在 XAML 中设置绑定以指向视图模型上的正确属性

    一般来说

    1. 我从不使用 ObjectDataProviders 或在 XAML 中实例化任何东西(问题太多)
    2. 始终使用 MVVM 模式
    3. 注意静态资源 - 每个应用实例只设置一次,动态资源可以更新

    【讨论】:

      【解决方案3】:

      是的,同意@AngelWPF 你应该使用 set DataContext as View.DataContext = ViewModel;

      【讨论】:

        【解决方案4】:

        您可以在视图的资源部分中实例化您的视图模型。创建新视图后 - 您将获得新的视图模型。

        此外,您将获得性能稍高且使用方便的静态绑定,因为您将获得智能感知。

        <Window x:Class="WpfApplication1.MainWindow"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication1="clr-namespace:WpfApplication1"
                Title="MainWindow" Height="350" Width="525">
            <Window.Resources>
                <WpfApplication1:MyViewModel x:Key="ViewModel"/>
            </Window.Resources>
            <Grid DataContext="{StaticResource ViewModel}">
                <ItemsControl ItemsSource="{Binding Data}"/>
            </Grid>
        </Window>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-10-23
          • 2011-10-29
          • 1970-01-01
          • 2011-01-20
          • 2011-01-20
          • 1970-01-01
          • 2012-02-20
          • 2015-06-05
          相关资源
          最近更新 更多