我是靠谱客的博主 粗暴小懒猪,这篇文章主要介绍WPF MVVM模式DataGrid1.构造MVVM基本功能类2.构造Model,ViewModel,现在分享给大家,希望可以做个参考。

1.构造MVVM基本功能类

因为没有使用MVVM框架,所以要自己构造两个MVVM的基本功能类,完成属性通知和命令绑定 

1.1 属性通知

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/// <summary> /// INotifyPropertyChanged 用于通知属性改变(实现ViewModel向View喊话,所有绑定该属性的都会得到通知) /// </summary> public class NotificationObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// 属性改变时调用该方法发出通知 /// </summary> /// <param name="propertyName"></param> public void RaisePropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } }

1.2 命令

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public class DelegateCommand<T> : ICommand { private readonly Action<T> _executeMethod = null; private readonly Func<T, bool> _canExecuteMethod = null; public DelegateCommand(Action<T> executeMethod) : this(executeMethod, null) { } public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod) { if (executeMethod == null) throw new ArgumentNullException("executeMetnod"); _executeMethod = executeMethod; _canExecuteMethod = canExecuteMethod; } #region ICommand 成员 /// <summary> /// Method to determine if the command can be executed /// </summary> public bool CanExecute(T parameter) { if (_canExecuteMethod != null) { return _canExecuteMethod(parameter); } return true; } /// <summary> /// Execution of the command /// </summary> public void Execute(T parameter) { if (_executeMethod != null) { _executeMethod(parameter); } } #endregion event EventHandler ICommand.CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } #region ICommand 成员 public bool CanExecute(object parameter) { if (parameter == null && typeof(T).IsValueType) { return (_canExecuteMethod == null); } return CanExecute((T)parameter); } public void Execute(object parameter) { Execute((T)parameter); } #endregion }

2.构造Model,ViewModel

复制代码
1
2
3
4
5
6
public class Person { public int ID { get; set; } public string Name { get; set; } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class PersonModel : NotificationObject { private bool _IsSelected = false; /// <summary> /// 是否选中 /// </summary> public bool IsSelected { get { return _IsSelected; } set { _IsSelected = value; this.RaisePropertyChanged(); } } private Person _Person; public Person Person { get { return _Person; } set { _Person = value; this.RaisePropertyChanged(); } } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
public class PersonListViewModel : NotificationObject { public PersonListViewModel() { _Persons.Add(new PersonModel() { Person = new Person() { ID = 1, Name = "张三" } }); _Persons.Add(new PersonModel() { Person = new Person() { ID = 2, Name = "李四" } }); _Persons.Add(new PersonModel() { Person = new Person() { ID = 3, Name = "王五" } }); _Persons.Add(new PersonModel() { Person = new Person() { ID = 4, Name = "赵六" } }); _Persons.Add(new PersonModel() { Person = new Person() { ID = 5, Name = "刘七" } }); _Persons.Add(new PersonModel() { Person = new Person() { ID = 6, Name = "陈八" } }); } private ObservableCollection<PersonModel> _Persons = new ObservableCollection<PersonModel>(); public ObservableCollection<PersonModel> Persons { get { return _Persons; } set { _Persons = value; this.RaisePropertyChanged(); } } private bool _IsSelectAll = false; public bool IsSelectAll { get { return _IsSelectAll; } set { _IsSelectAll = value; RaisePropertyChanged(); } } private ICommand _SelectAllCommand; public ICommand SelectAllCommand { get { return _SelectAllCommand ?? (_SelectAllCommand = new DelegateCommand<object>(SelectAll)); } } /// <summary> /// 全选 /// </summary> /// <param name="id"></param> public void SelectAll(object id) { foreach (var item in Persons) { item.IsSelected = IsSelectAll; } } private ICommand _SelectCommand; public ICommand SelectCommand { get { return _SelectCommand ?? (_SelectCommand = new DelegateCommand<int>(Select)); } } /// <summary> /// 单选 /// </summary> /// <param name="id"></param> public void Select(int id) { PersonModel md = Persons.Where(p => p.Person.ID == id).FirstOrDefault(); if (md != null) { if (!md.IsSelected && IsSelectAll) { IsSelectAll = false; } else if (md.IsSelected && !IsSelectAll) { foreach (var item in Persons) { if (!item.IsSelected) return; } IsSelectAll = true; } } } /// <summary> /// 判断是否选中 /// </summary> /// <param name="onlyOne">是否单选</param> /// <returns></returns> public bool SelectValidate(bool onlyOne = false) { if (this.Persons.Count(p => p.IsSelected) < 1) { MessageBox.Show("未勾选数据!"); return false; } if (onlyOne) { if (this.Persons.Count(p => p.IsSelected) > 1) { MessageBox.Show("只能勾选一条数据!"); return false; } } return true; } private ICommand _DelCommand; public ICommand DelCommand { get { return _DelCommand ?? (_DelCommand = new DelegateCommand<object>(Del)); } } /// <summary> /// 删除 /// </summary> /// <param name="obj"></param> public void Del(object obj = null) { if (!SelectValidate()) return; MessageBoxResult result = MessageBox.Show("是否删除选中项?", "提示", MessageBoxButton.YesNo); if (result != MessageBoxResult.Yes) { return; } StringBuilder sb = new StringBuilder(); bool hasSelect = false; //获取选中的数据 foreach (var v in _Persons) { if (v.IsSelected) { sb.Append(v.Person.Name + ";"); hasSelect = true; } } if (!hasSelect) { MessageBox.Show("请选择修改项", "警告"); return; } MessageBox.Show("选中 " + sb.ToString()); } private ICommand _EditCommand; public ICommand EditCommand { get { return _EditCommand ?? (_EditCommand = new DelegateCommand<object>(Edit)); } } /// <summary> /// 修改 /// </summary> /// <param name="obj"></param> public void Edit(object obj = null) { if (!SelectValidate(true)) return; PersonModel model = null; bool hasSelect = false; //获取选中的数据 foreach (var v in _Persons) { if (v.IsSelected) { model = v; hasSelect = true; break; } } if (!hasSelect) { MessageBox.Show("请选择修改项", "警告"); return; } MessageBox.Show("选中 " + model.Person.Name); } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<!--uc_PersonList.xaml--> <!--需要将Checkbox的点击事件绑定到Command命令,引用System.Windows.Interactivity程序集可实现Event to Command功能,方式:引用 => 程序集 => 扩展 => System.Windows.Interactivity --> <UserControl x:Class="MvvmDataGridCheckBoxSelectAll.uc_PersonList" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:MvvmDataGridCheckBoxSelectAll" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" mc:Ignorable="d"> <UserControl.DataContext> <local:PersonListViewModel /> </UserControl.DataContext> <DockPanel Margin="0"> <StackPanel DockPanel.Dock="Top" Orientation="Horizontal"> <Button Command="{Binding EditCommand}" ToolTip="修改"> <Button.Content> <StackPanel Orientation="Horizontal" > <Image Stretch="None" VerticalAlignment="Center" Source="../Images/List_Edit.png"/> <TextBlock Text="修改" VerticalAlignment="Center"/> </StackPanel> </Button.Content> </Button> <Button Command="{Binding DelCommand}" ToolTip="删除"> <Button.Content> <StackPanel Orientation="Horizontal" > <Image Stretch="None" VerticalAlignment="Center" Source="../Images/List_Del.png"/> <TextBlock Text="删除" VerticalAlignment="Center"/> </StackPanel> </Button.Content> </Button> <!--<Button Command="{Binding RefreshCommand}" ToolTip="刷新"> <Button.Content> <StackPanel Orientation="Horizontal" > <Image Stretch="None" VerticalAlignment="Center" Source="../Images/List_Refresh.png"/> <TextBlock Text="刷新" VerticalAlignment="Center"/> </StackPanel> </Button.Content> </Button>--> </StackPanel> <DataGrid x:Name="dataGrid" AutoGenerateColumns="False" GridLinesVisibility="None" CanUserAddRows="False" Focusable="False" Margin="0" HorizontalAlignment="Left" VerticalAlignment="Top" ItemsSource="{Binding Persons}" Width="Auto" EnableColumnVirtualization="False"> <DataGrid.ColumnHeaderStyle> <Style TargetType="DataGridColumnHeader"> <Setter Property="HorizontalContentAlignment" Value="Center"> </Setter> </Style> </DataGrid.ColumnHeaderStyle> <DataGrid.Columns> <DataGridTemplateColumn> <DataGridTemplateColumn.Header> <CheckBox IsChecked="{Binding DataContext.IsSelectAll,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,RelativeSource={RelativeSource AncestorType=UserControl, AncestorLevel=1 }}"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <i:InvokeCommandAction Command="{Binding DataContext.SelectAllCommand ,RelativeSource={RelativeSource AncestorType=UserControl, AncestorLevel=1 }}" ></i:InvokeCommandAction> </i:EventTrigger> </i:Interaction.Triggers> </CheckBox> </DataGridTemplateColumn.Header> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox Margin="3" IsChecked="{Binding IsSelected,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <i:InvokeCommandAction Command="{Binding DataContext.SelectCommand ,RelativeSource={RelativeSource AncestorType=UserControl, AncestorLevel=1 }}" CommandParameter="{Binding Person.ID}" ></i:InvokeCommandAction> </i:EventTrigger> </i:Interaction.Triggers> </CheckBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTextColumn Binding="{Binding Person.Name}" Header="姓名" IsReadOnly="True" Width="*"></DataGridTextColumn> </DataGrid.Columns> </DataGrid> </DockPanel> </UserControl>

 

最后

以上就是粗暴小懒猪最近收集整理的关于WPF MVVM模式DataGrid1.构造MVVM基本功能类2.构造Model,ViewModel的全部内容,更多相关WPF内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(100)

评论列表共有 0 条评论

立即
投稿
返回
顶部