从Nuget中下载包
1、mvvmlights
2、propertyChanged(需要加载)并继承inotyporpertychanged
3、System.Windows.Interactivity.WPF
创建文件夹
ViewModel文件夹
新建文本ViewModelLocator
//导入命名空间
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Ioc;
public ViewModelLocator()
{
SimpleIoc.Default.Register<MainViewModel>();
}
public MainViewModel Main
{
get { return SimpleIoc.Default.GetInstance<MainViewModel>(); }
}
新建界面的ViewModel文件
using galasoft.Mvvmlight
public class MainViewModel:ViewModelBase
{
}
修改app.xaml
///引入 viewmodellocator的命名空间
xmlns:vm="clr-namespace:YanTai.LB.Excel.ViewModel"
<ResourceDictionary>
<vm:ViewModelLocator x:Key="Locator"/>
</ResourceDictionary>
修改View
//方法1:需要配置app.xml
<Window.DataContext>
<Binding Path="Main" Source="{StaticResource Locator}"/>
</Window.DataContext>
//方法2:不需要配置app.xml
xmlns:vm="clr-namespace:textmvvm.ViewModel"
<Window.DataContext>
<vm:MainViewModel />
</Window.DataContext>
新建Model
使用model类可以方便后期的调用也简化了后期的代码量
自定义类字段可以继承于observableobject,最好都要继承
///引入命名空间
using GalaSoft.MvvmLight;
public class MainModel:ObservableObject
{
public string Title { set; get; }
public string Submit { set; get; }
public Studen student{set;get;}
}
public class Studen:INotifyPropertyChanged
{
public string Name{set;get;}
public string Age{set;get;}
}
需要导入dllpropertyChanged。
引入窗体事件
xmlns:intr="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
<intr:Interaction.Triggers>
<intr:EventTrigger EventName="KeyDown">
<intr:InvokeCommandAction Command="{Binding TB_MouseDown }"
</intr:EventTrigger>
</intr:Interaction.Triggers>
输入框中的按键指令和鼠标操作可采用如下方式
<TextBox x:Name="TB_ProductType"
Grid.Column="1"
BorderThickness="0,0,0,2"
FontSize="20"
VerticalContentAlignment="Bottom"
Text="{Binding Model.product.Product_Type}">
<TextBox.InputBindings>
<KeyBinding Command="{Binding TB_MouseDown}"
Key="Enter"
CommandParameter="{Binding ElementName=TB_ProductType, Path=Text}"/>
</TextBox.InputBindings>
</TextBox>
<border>
<contentcontrol content="{binding usercontrol"/>
</border>
在viewModel中需要引入using system.windows.control
然后和属性一样绑定