【发布时间】: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 表单设计器始终运行表单/控件的构造函数,只需将代码移动到加载事件(请参阅下面的答案),或根据控件交互手动进行。