【问题标题】:How to load a View model when Window or view is loaded加载窗口或视图时如何加载视图模型
【发布时间】:2013-11-06 15:06:32
【问题描述】:

我在 C# 中创建了一个带有视图模型的简单应用程序,通常您必须在窗口或用户控件的数据上下文中声明视图模型才能加载它。问题是只要 Visual Studio 打开应用程序,它就会加载。

我希望它在应用程序运行并加载窗口时加载。

<Window x:Class="GraphApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ViewModel="clr-namespace:GraphApp"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <!-- Insert Model view Here. I want it to load when the window is running, not when I have it opened in visual studio.-->

    </Window.DataContext>

这可能吗?

【问题讨论】:

  • 为什么在 Designer 中加载 ViewModel 对您来说是个问题?
  • 打开窗口(运行应用程序)时视图模型是否未加载?我不确定您所说的“在 Visual Studio 中加载”是什么意思...
  • 你的意思是在Visual Studio表单设计器中加载?
  • 是的,我的意思是从表单设计器加载。每次在我的环境中加载窗口时都会弹出一个窗口,它意味着在客户的环境中加载。我只是想要一种方法来防止这种情况发生。
  • Visual Studio 表单设计器始终运行表单/控件的构造函数,只需将代码移动到加载事件(请参阅下面的答案),或根据控件交互手动进行。

标签: c# wpf xaml


【解决方案1】:

通常,当我们希望在元素加载后发生某些事情时,我们会处理FrameworkElement.Loaded event

public MainWindow()
{
    InitializeComponent();
    Loaded += MainWindow_Loaded;
}

private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    DataContext = new ViewModel();
}

更新>>>

实现此目的的另一种方法是设置一些 DataTemplates 并具有您的视图模型类型或公共基础视图模型类的属性:

public BaseViewModel ViewModel { get; set; } // Implement INotifyPropertyChanged here

然后在App.xaml Resources:

<DataTemplate DataType="{x:Type ViewModels:FirstViewModel}">
    <Views:FirstTrackView />
</DataTemplate>
...
<DataTemplate DataType="{x:Type ViewModels:LastViewModel}">
    <Views:LastTrackView />
</DataTemplate>

然后你可以这样隐式设置DataContext,只要你喜欢,就会自动显示相应的视图:

ViewModel = new SomeViewModel();

【讨论】:

  • 这可能是唯一的办法。
【解决方案2】:

附加到Window.Loaded 事件并:

void OnLoad(object sender, RoutedEventArgs e)
{
    //Check if the event is not raised by the visual studio designer
    if(DesignerProperties.GetIsInDesignMode(this))
      return;

    //Set the data context:
    this.DataContext = //Your viewmodel here
}

【讨论】:

    【解决方案3】:

    我知道这已经过时了,但您可以通过首先添加视图模型所在的命名空间来实现这一点。

    xmlns:vm="clr-namespace:MyWpfForm.ViewModel"
    

    然后将其直接添加到您的关闭窗口元素下

    <Control.DataContext>
       <vm:MainWindowViewModel />
    </Control.DataContext>
    

    “MainWindowViewModel”是您的视图模型的构造函数。

    【讨论】:

      猜你喜欢
      • 2013-07-02
      • 2015-06-25
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      相关资源
      最近更新 更多