1.实体类的编写
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using GalaSoft.MvvmLight; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MVVM.Model { public class User:ObservableObject { //public int ID { get; set; } //public String Username { get; set; } //public String Nickname { get; set; } // public String Address { get; set; } public int ID { get { return _id; } set { Set(() => ID, ref _id, value); } } private int _id; public String Username { get { return _username; } set { Set(() => Username, ref _username, value); } } private String _username; public String Nickname { get { return _nickname; } set { Set(() => Nickname, ref _nickname, value); } } private String _nickname; public String Address { get { return _address; } set { Set(() => Address, ref _address, value); } } private String _address; public User(int id,String uname,String nname,String address) { this.ID = id; this.Username = uname; this.Nickname = nname; this.Address = address; } public User() { } } }
2.ViewModel和View的编写
SelectedItem的效果
View中DataGrid的Binding使用方法
点击按钮“点击我”后,会触发当前项的变化和用户名的变化
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<Window x:Class="MVVM.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:command="http://www.galasoft.ch/mvvmlight" Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <Binding Path="Main" Source="{StaticResource Locator}"></Binding> </Window.DataContext> <Grid> <Grid.Resources> <Style x:Key="BackColor" TargetType="Rectangle"> <Setter Property="Fill" Value="Black"></Setter> </Style> </Grid.Resources> <Grid.RowDefinitions> <RowDefinition Height="4*"></RowDefinition> <RowDefinition Height="*"></RowDefinition> </Grid.RowDefinitions> <DataGrid Name="myDataGrid" SelectedItem="{ Binding SelectedUserItem}" ItemsSource="{ Binding UserList}" AutoGenerateColumns="False" CanUserAddRows="False" MaxHeight="150"> <DataGrid.CellStyle> <Style> </Style> </DataGrid.CellStyle> <DataGrid.Columns> <DataGridTemplateColumn Header="序号" Width="80"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding ID}"></TextBlock> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTextColumn Header="序号" Width="80" Binding="{Binding ID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> <DataGridTemplateColumn Header="用户名" Width="80"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Username}"></TextBlock> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTextColumn Header="序号" Width="80" Binding="{Binding Username, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> <DataGridTemplateColumn Header="昵称" Width="80"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Nickname}"></TextBlock> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="地址" Width="80"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Address}"></TextBlock> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="操作" Width="40"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox ></CheckBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTextColumn Header="部门名称" Width="80" Binding="{Binding Department, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> </DataGrid.Columns> </DataGrid> <StackPanel Grid.Row="1"> <Button Content="点击我" Command="{Binding ClickCommand}"></Button> </StackPanel> </Grid> </Window>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.CommandWpf; using System.Text.RegularExpressions; using System.Windows.Input; using System.Net; using System.IO; using System.Text; using System.Security.Cryptography.X509Certificates; using System.Net.Security; using System.Collections.Generic; using Newtonsoft.Json; using System; using System.Runtime.InteropServices; using System.Xml; using MVVM.Model; using System.Xml.Linq; using System.Windows; using MVVM.communication; using System.Threading; using Microsoft.Win32; using MVVM.Service; using MVVM.ftp; using System.Linq; using System.Collections.ObjectModel; namespace MVVM.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 { public ICommand ClickCommand { get; set; } public ObservableCollection<User> UserList//ObservableCollection { get { return _userList; } set { Set(() => UserList, ref _userList, value); } } private ObservableCollection<User> _userList = new ObservableCollection<User>(); public User SelectedUserItem { get { return _selectedUserItem; } set { Set(() => SelectedUserItem, ref _selectedUserItem, value); } } private User _selectedUserItem; public String Department { get { return _department; } set { Set(() => Department, ref _department, value); } } private String _department; public MainViewModel() { Department = "服务部"; User u1 = new User(1,"zhangsan","zhang","bj"); User u2 = new User(2, "list", "zhang", "bj"); User u3 = new User(3, "wangwu", "zhang", "bj"); User u4 = new User(4, "zhaol", "zhang", "bj"); User u5 = new User(5, "chenq", "zhang", "bj"); UserList.Add(u1); UserList.Add(u2); UserList.Add(u3); UserList.Add(u4); UserList.Add(u5); ClickCommand = new RelayCommand(myMethod); SelectedUserItem = UserList[3]; } public void myMethod(){ SelectedUserItem = UserList[1]; UserList[2].Username = "my name changed"; } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/* In App.xaml: <Application.Resources> <vm:ViewModelLocator xmlns:vm="clr-namespace:MVVM" 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; using MVVM.Service; namespace MVVM.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); ////if (ViewModelBase.IsInDesignModeStatic) ////{ //// // Create design time view services and models //// SimpleIoc.Default.Register<IDataService, DesignDataService>(); ////} ////else ////{ //// // Create run time view services and models //// SimpleIoc.Default.Register<IDataService, DataService>(); ////} SimpleIoc.Default.Register<ICallPythonService,CallPythonService>(); SimpleIoc.Default.Register<MainViewModel>(); SimpleIoc.Default.Register<VCFCViewModel>(); SimpleIoc.Default.Register<TestViewModel>(); SimpleIoc.Default.Register<CasInspectionViewModel>(); SimpleIoc.Default.Register<MemoryLeakViewModel>(); } public MainViewModel Main { get { return ServiceLocator.Current.GetInstance<MainViewModel>(); } } public VCFCViewModel VCFC { get { return ServiceLocator.Current.GetInstance<VCFCViewModel>(); } } public TestViewModel Test { get { return ServiceLocator.Current.GetInstance<TestViewModel>(); } } public CasInspectionViewModel CasInspection { get { return ServiceLocator.Current.GetInstance<CasInspectionViewModel>(); } } public MemoryLeakViewModel MemoryLeak { get { return ServiceLocator.Current.GetInstance<MemoryLeakViewModel>(); } } public static void Cleanup() { // TODO Clear the ViewModels } } }
有点儿不明白的地方