[英]Referencing ViewModel from View's DataContext Prevents XAML Designer edits
I am trying to "hook up" my viewmodel as a DataContext to my View. 我试图将我的视图模型作为DataContext连接到我的视图。 I am going with an application-wide one view-to-viewmodel scenario. 我正在处理一个应用程序范围内的“从视图到视图”模型的场景。
I like the idea of using the following method to attach (which it does successfully): 我喜欢使用以下方法进行附加(成功完成)的想法:
<UserControl ......Window Stuff.......>
<UserControl.DataContext >
<vm:MyViewModel/>
</UserControl.DataContext>
</UserControl>
However the xaml editor places a purple squiggly line under <vm:MyViewModel/>
and hovertext gives error 但是,xaml编辑器在<vm:MyViewModel/>
下放置了一条紫色的波浪线,并且hovertext提供了错误
"Cannot create instance of vm:MyViewModel"
But it correctly builds/runs my application and presents the data, which the method: 但是它可以正确构建/运行我的应用程序并显示数据,该方法如下:
<UserControl>
<UserControl.Resources>
<DataTemplate DataType="{x:Type vm:MyViewModel}">
<vw:MyView/>
</DataTemplate>
</UserControl.Resources>
</UserControl>
Does NOT present my data, although it appears to be acceptable code. 尽管它似乎是可接受的代码,但不显示我的数据。
Commenting-out the DataContext reference is really a pain just for making edits to the controls manually. 仅手动对控件进行编辑,注释掉DataContext参考确实很痛苦。 Am I doing something incorrectly/am I forgetting something? 我做错了什么/我忘记了什么吗?
Thanks in advance! 提前致谢! :) :)
There is likely something going on in the constructor of your view model that is preventing the model from being instantiated within Visual Studio. 视图模型的构造函数中可能正在发生某种情况,阻止了在Visual Studio中实例化模型。
Try adding a return
statement before anything is done in the view model's constructor, rebuild and see if the error goes away. 在视图模型的构造函数中完成任何操作之前,请尝试添加return
语句,然后重新构建并查看错误是否消失。
Here's an extension method that will determine if the the current process is within visual studio: 这是一个扩展方法,它将确定当前进程是否在Visual Studio中:
public static class Extensions
{
/// <summary>
/// Extension method to determine if the current process is executing
/// code within the Visual Studio designer or not.
/// </summary>
public static bool IsVisualStudioDesigner( this Process process )
{
return process.MainModule.ModuleName.Contains( "devenv.exe" );
}
}
And then in your constructor: 然后在您的构造函数中:
public ctor()
{
if ( Process.GetCurrentProcess().IsVisualStudioDesigner() )
return;
// do constructor stuff
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.