关于C# WPF创建MvvMLight无法自动生成ViewModel文件
在这里我想到的解决问题是,直接抄源码,自己手动创建一个一样的,虽然有点麻烦,但是还是比较靠谱的方案。
需要手动创建ViewModel文件夹
右击项目->添加->文件夹,命名为ViewModel。
在这个ViewModel文件夹下创建两个Class文件
分别命名为ViewModelLocator.cs和MainViewModel.cs
其中ViewModelLocator.cs文件的内容为:
/*
In App.xaml:
<Application.Resources>
<vm:ViewModelLocator xmlns:vm="clr-namespace:HelloMvvmLight"
x:Key="Locator" />
</Application.Resources>
In the View:
DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}"
You can also use Blend to do all this with the tool's support.
See http://www.galasoft.ch/mvvm
*/
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Ioc;
using Microsoft.Practices.ServiceLocation;
namespace HandEyeTranslationApp.ViewModel
{
/// <summary>
/// This class contains static references to all the view models in the
/// application and provides an entry point for the bindings.
/// </summary>
public class ViewModelLocator
{
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<MainViewModel>();
}
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
public static void Cleanup()
{
// TODO Clear the ViewModels
}
}
}
注意:这里的namespace下的HandEyeTranslationApp是我项目的名称,你需要替换为你项目的名称。
另一个文件,MainViewModel.cs源码如下:
using GalaSoft.MvvmLight;
namespace HandEyeTranslationApp.ViewModel
{
/// <summary>
/// This class contains properties that the main View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class MainViewModel : ViewModelBase
{
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
}
}
}
同样将这里的namespace下的HandEyeTranslationApp替换为你项目的名称。
最重要一点App.xaml文件修改
需要对App.xaml文件进行修改,为保险起见建议直接复制一下内容,再进行替换。
<Application x:Class="HandEyeTranslationApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:HandEyeTranslationApp"
StartupUri="MainWindow.xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
d1p1:Ignorable="d"
xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006">
<Application.Resources>
<ResourceDictionary>
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" xmlns:vm="clr-namespace:HandEyeTranslationApp.ViewModel"/>
</ResourceDictionary>
</Application.Resources>
</Application>
同样将这里的所有HandEyeTranslationApp替换为你项目的名称。
至此完毕!