WPF+MVVM学习总结 DataGrid简单案例

时间:2021-10-02 14:59:28

一、WPF概要

WPF(Windows Presentation Foundation)是微软推出的基于Windows 的用户界面框架,属于.NET Framework 3.0的一部分。它提供了统一的编程模型、语言和框架,真正做到了分离界面设计人员与开发人员的工作;同时它提供了全新的多媒体交互用户图形界面。

1.1、 MVVM简介

  在WPF中,MVVM(View-ViewModel-Model)开发模型用的很多,它具有低耦合,可重用行,相对独立的设计和逻辑。所以备受广大开发者的喜爱。View 说白了就是前台界面,ViewModel 是连接层(类似于MVC中的Controller),他将Model 层和View层结合起来,并封装好命令,供View层绑定,Model层提供类的对象,供ViewModel可以轻松的访问数据库。MVVM是典型的WPF设计模式,view通过命令将所有用户的输入传递给viewmodel。view通过数据绑定从viewmodel中获得数据。model不了解viewmodel的情况,viewmodel不了解view的情况

WPF+MVVM学习总结 DataGrid简单案例

二、简单案例DataGrid Binding显示数据

1.Model:Model就是一个class,是对现实中事物的抽象,开发过程中涉及到的事物都可以抽象为Model,例如客户,客户的姓名、编号、电话、住址等属性也对应了class中的Property,客户的下订单、付款等行为对应了class中的方法。

2. View:View很好理解,就是视图界面。

3. ViewModel:上面说过Model抽象,那么ViewModel就是对View的抽象。显示的数据对应着ViewMode中的Property,执行的命令对应着ViewModel中的Command。

(通过一个例子来解释MVVM 让我使用MVVM创建一个简单的用户管理应用程序。按部就班我们必须首先定义Model(模式),然后定义ViewModel,最后定义View。)

2.1、创建Model

public class User
{
/// <summary>
/// 编号
/// </summary>
public int ID { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; } /// <summary>
/// 年龄
/// </summary>
public int Age { get; set; } /// <summary>
/// 性别
/// </summary>
public string Sex { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Remarks { get; set; }
}

2.2、创建ViewModel

字面上看,ViewModel的意思是“视图 模型”,也可以被认为是view的抽象,但是它也是一个特殊化的模式,并且其view可以使用数据绑定。最新的角色,ViewModel包含了一个数据传送器,即将Model中的数据传送到View中。ViewModel中同样包含了一些命令,这样可以使得View可以与Model进行交互。

public class UserViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChanged(string propertyName)
{
if (propertyName != null)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}

在ViewModel中增加一个类UserViewModel ,这个类用来实现INotifyPropertyChanged接口。

public class ShowDataViewModel : UserViewModel
{
//数据源
ObservableCollection<User> _mylist = new ObservableCollection<User>();
public ObservableCollection<User> mylist
{ get { return _mylist; }
set
{
_mylist = value;
RaisePropertyChanged("mylist");
}
}
     //构造函数
public ShowDataViewModel()
{
mylist.Add(new User() { ID = , Name = "张三", Age = , Sex = "女", Remarks = "无" });
mylist.Add(new User() { ID = , Name = "李四", Age = , Sex = "女", Remarks = "无" });
mylist.Add(new User() { ID = , Name = "王五", Age = , Sex = "女", Remarks = "无" });
mylist.Add(new User() { ID = , Name = "赵六", Age = , Sex = "女", Remarks = "无" });
} }

在创建一个类ShowDataViewModel,继承UserViewModel 添加测试数据

2.3、创建View

View在MAML中定义的,并且在后台不用写代码,View不应该含有任何的逻辑。它仅仅通过数据绑定就能达到显示。

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
xmlns:vm="clr-namespace:WpfApplication1.ViewModel"
Title="MainWindow" Height="350" Width="413">
<Window.DataContext>
<vm:ShowDataViewModel/>
</Window.DataContext>
<Grid Margin="0,0,2,0">
<DataGrid x:Name="dataGrid" AutoGenerateColumns="False" HorizontalAlignment="Left" VerticalAlignment="Top" ItemsSource="{Binding mylist}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding ID}" Header="编号"/>
<DataGridTextColumn Binding="{Binding Name}" Header="姓名" Width="100"/>
<DataGridTextColumn Binding="{Binding Age}" Header="年龄"/>
<DataGridTextColumn Binding="{Binding Sex}" Header="性别" Width="60"/>
<DataGridTextColumn Binding="{Binding Remarks}" Header="备注" Width="172"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
xmlns:vm="clr-namespace:WpfApplication1.ViewModel"
<Window.DataContext>
<vm:ShowDataViewModel/>
</Window.DataContext>

引入一下命名空间完成上面绑定然后给DataGrid 绑定一下ItemsSource不用运行就能直接看到数据在控件上面显示

WPF+MVVM学习总结 DataGrid简单案例

以上就完成了简单的数据显示

三、DataGrid的增改删功能

3.1、数据绑定

3.1.1、wpf中的数据绑定

在wpf中界面中绑定了数据源后,数据在界面上的修改能反映到绑定源

WPF+MVVM学习总结 DataGrid简单案例

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
xmlns:vm="clr-namespace:WpfApplication1.ViewModel"
Title="MainWindow" Height="337" Width="419">
<Window.DataContext>
<vm:ShowDataViewModel/>
</Window.DataContext>
<Grid Margin="0,0,2,182">
<DataGrid x:Name="dataGrid" SelectionUnit="FullRow" IsReadOnly="True" AutoGenerateColumns="False" HorizontalAlignment="Left" VerticalAlignment="Top" ItemsSource="{Binding mylist}" Height="135" Margin="1,0,0,-11">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding ID}" Header="编号"/>
<DataGridTextColumn Binding="{Binding Name}" Header="姓名" Width="100"/>
<DataGridTextColumn Binding="{Binding Age}" Header="年龄"/>
<DataGridTextColumn Binding="{Binding Sex}" Header="性别" Width="60"/>
<DataGridTextColumn Binding="{Binding Remarks}" Header="备注" Width="172"/>
</DataGrid.Columns>
</DataGrid>
<Label x:Name="labID" Content="编号:" HorizontalAlignment="Left" Margin="17,152,0,-53"/>
<TextBox x:Name="txtID" IsEnabled ="False" Text="{Binding ID}" HorizontalAlignment="Left" Height="22" Margin="63,154,0,-52" TextWrapping="Wrap" Width="60"/>
<Label x:Name="labName" Content="姓名:" HorizontalAlignment="Left" Margin="143,154,0,-55" />
<TextBox x:Name="txtName" Text="{Binding Name}" HorizontalAlignment="Left" Height="22" Margin="189,152,0,-50" TextWrapping="Wrap" Width="62"/>
<Label x:Name="labPAge" Content="年龄:" HorizontalAlignment="Left" Margin="273,152,0,-53" VerticalAlignment="Top" RenderTransformOrigin="-0.233,0.68"/>
<TextBox x:Name="txtAge" Text="{Binding Age}" HorizontalAlignment="Left" Height="22" Margin="319,152,0,-50" TextWrapping="Wrap" Width="58"/>
<Label x:Name="labSex" Content="性别:" HorizontalAlignment="Left" Margin="17,188,0,-89" RenderTransformOrigin="-0.233,0.68"/>
<ComboBox Text="{Binding Sex}" SelectedIndex="0" x:Name="comboBox" HorizontalAlignment="Left" Margin="63,191,0,-88" Width="61">
<ComboBoxItem Tag="1" Content="男"/>
<ComboBoxItem Tag="2" Content="女"/>
</ComboBox>
<Label x:Name="labRemarks" Content="备注:" HorizontalAlignment="Left" Margin="144,187,0,-88" VerticalAlignment="Top" RenderTransformOrigin="-0.233,0.68"/>
<TextBox x:Name="txtRemarks" Text="{Binding Remarks}" HorizontalAlignment="Left" Height="22" Margin="189,184,0,-82" TextWrapping="Wrap" VerticalAlignment="Top" Width="188" RenderTransformOrigin="0.5,0.5"/>
<Button x:Name="butSave" Command="{Binding AddCommand}" Content="新增" HorizontalAlignment="Left" Margin="70,240,0,-135" VerticalAlignment="Top" Width="69" Height="19" RenderTransformOrigin="0.466,0.941"/>
<Button x:Name="butUpdate" Command="{Binding UpdateCommand}" Content="修改" HorizontalAlignment="Left" Margin="160,240,0,-135" VerticalAlignment="Top" Width="69" Height="19" RenderTransformOrigin="0.466,0.941"/>
<Button x:Name="butDelete" Command="{Binding DeleteCommand}" Content="删除" HorizontalAlignment="Left" Margin="250,240,0,-135" VerticalAlignment="Top" Width="69" Height="19" RenderTransformOrigin="0.466,0.941"/>
</Grid>
</Window>

3.2、命令绑定

在上面代码我们给按钮 Command 绑定了 Add Update Delete,接下来我们就开始实现功能

我们新建一个文件DelegateCommands.cs  实现接口ICommand

public class DelegateCommands : ICommand
{
public Action<object> ExecuteCommand = null; public Func<object, bool> CanExecuteCommand = null; //当命令可执行状态发生改变时,应当被激发
public event EventHandler CanExecuteChanged; //用于判断命令是否可以执行
public bool CanExecute(object parameter)
{
if (CanExecuteCommand != null)
{
return this.CanExecuteCommand(parameter);
}
else
{
return true;
}
}
//命令执行
public void Execute(object parameter)
{
if (this.ExecuteCommand != null) this.ExecuteCommand(parameter);
} }

回到ShowDataViewModel.cs 定义下面命令

 public DelegateCommands AddCommand { get; set; }
public DelegateCommands UpdateCommand { get; set; }
public DelegateCommands DeleteCommand { get; set; }

把操作对应的方法写好

#region 方法
private void Binding()
{
ShowList.Clear();
mylist.ToList().ForEach(p => ShowList.Add(p));
}
public void addStudent(object parameter)
{
int id = mylist[mylist.Count-].ID;
mylist.Add(new User() { ID= id + , Name=Name,Age=Age,Sex=Sex,Remarks=Remarks});
Binding();
}
public void updateStudent(object parameter)
{
if (ID == )
{
MessageBox.Show("请选择修改项");
return;
}
foreach (var item in mylist)
{
if (item.ID==user.ID)
{
item.ID =ID;
item.Name = Name;
item.Sex = Sex;
item.Remarks = Remarks;
item.Age = Age;
break;
}
}
Binding();
}
public void deleteStudent(object parameter)
{
if (ID == )
{
MessageBox.Show("请选择删除项");
return;
}
User user1 = mylist.Single(p => p.ID == ID);
mylist.Remove(user1);
Binding();
}
#endregion

在进行绑定一下这样我们就能实现增删改了

 public ShowDataViewModel()
{
AddCommand = new DelegateCommands();
AddCommand.ExecuteCommand = new Action<object>(addStudent); UpdateCommand = new DelegateCommands();
UpdateCommand.ExecuteCommand = new Action<object>(updateStudent);//修改方法 DeleteCommand = new DelegateCommands();
DeleteCommand.ExecuteCommand = new Action<object>(deleteStudent);//修改方法 mylist.Add(new User() { ID = , Name = "张三", Age = , Sex = "女", Remarks = "无" });
mylist.Add(new User() { ID = , Name = "李四", Age = , Sex = "女", Remarks = "无" });
mylist.Add(new User() { ID = , Name = "王五", Age = , Sex = "女", Remarks = "无" });
mylist.Add(new User() { ID = , Name = "赵六", Age = , Sex = "女", Remarks = "无" }); Binding();
}

3.3、事件绑定

如果我们想点击控件里面的一行,下面对应的文本框就显示我们该怎么样呢?

回到View给DataGrid绑定事件 首先我们需要给项目添加引用:System.Windows.Interactivity 并且给页面引用命名空间

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
<DataGrid  SelectionUnit="FullRow" AutoGenerateColumns="False" IsReadOnly="True" ItemsSource="{Binding ShowList,Mode=TwoWay}" x:Name="dataGrid" VerticalAlignment="Top" Height="182" HorizontalAlignment="Left" Width="408">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged" >
<i:InvokeCommandAction Command="{Binding SelectionChangedCommand}" CommandParameter="{Binding ElementName=dataGrid}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding ID}" Header="编号"/>
<DataGridTextColumn Binding="{Binding Name}" Header="姓名" Width="100"/>
<DataGridTextColumn Binding="{Binding Age}" Header="年龄"/>
<DataGridTextColumn Binding="{Binding Sex}" Header="性别" Width="60"/>
<DataGridTextColumn Binding="{Binding Remarks}" Header="备注" Width="172"/>
</DataGrid.Columns>
</DataGrid>

我们在这里CommandParameter参数传的是控件dataGrid

然后我们去ViewModel  ShowDataViewModel.cs

public ICommand SelectionChangedCommand
{
get
{
return new DelegateCommand<DataGrid>((datagrid) =>
{
if (datagrid.SelectedItems.Count > )
{
user =(User)datagrid.SelectedItems[];
ID = user.ID;
Name = user.Name;
Age = user.Age;
Sex = user.Sex;
Remarks = user.Remarks;
}
});
}
}

上一步 需添加引用 Microsoft.Practices.Prism.dll 这样就完成了

这样一个小案例就完成了。