WPF 使用MVVM的增删改查例子
时间: 2023-07-20 16:08:12 浏览: 199
以下是一个简单的使用MVVM实现增删改查的WPF例子:
Model类:
```csharp
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
```
ViewModel类:
```csharp
public class PersonViewModel : INotifyPropertyChanged
{
private ObservableCollection<Person> _people;
public ObservableCollection<Person> People
{
get { return _people; }
set
{
if (_people != value)
{
_people = value;
OnPropertyChanged("People");
}
}
}
private Person _selectedPerson;
public Person SelectedPerson
{
get { return _selectedPerson; }
set
{
if (_selectedPerson != value)
{
_selectedPerson = value;
OnPropertyChanged("SelectedPerson");
}
}
}
public ICommand AddCommand { get; set; }
public ICommand UpdateCommand { get; set; }
public ICommand DeleteCommand { get; set; }
public PersonViewModel()
{
// 初始化数据
People = new ObservableCollection<Person>
{
new Person { Id=1, Name="Tom", Age=20 },
new Person { Id=2, Name="Jerry", Age=30 },
};
// 添加命令
AddCommand = new RelayCommand(AddPerson);
// 修改命令
UpdateCommand = new RelayCommand(UpdatePerson, CanUpdatePerson);
// 删除命令
DeleteCommand = new RelayCommand(DeletePerson, CanDeletePerson);
}
private void AddPerson()
{
// 创建新实例
var person = new Person();
// 将新实例添加到列表中
People.Add(person);
// 设置选中项为新实例
SelectedPerson = person;
}
private void UpdatePerson()
{
// 更新选中项
SelectedPerson.Name = "New Name";
SelectedPerson.Age = 25;
}
private bool CanUpdatePerson()
{
// 如果没有选中项,则不能修改
return SelectedPerson != null;
}
private void DeletePerson()
{
// 删除选中项
People.Remove(SelectedPerson);
// 清空选中项
SelectedPerson = null;
}
private bool CanDeletePerson()
{
// 如果没有选中项,则不能删除
return SelectedPerson != null;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
```
View:
```xml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
DataContext="{StaticResource PersonViewModel}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal">
<Button Content="Add" Command="{Binding AddCommand}"/>
<Button Content="Update" Command="{Binding UpdateCommand}"/>
<Button Content="Delete" Command="{Binding DeleteCommand}"/>
</StackPanel>
<ListBox Grid.Row="1" ItemsSource="{Binding People}"
SelectedItem="{Binding SelectedPerson}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding Age}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
```
在View中设置DataContext为ViewModel实例,并绑定AddCommand、UpdateCommand和DeleteCommand到Button的Command属性上,绑定People到ListBox的ItemsSource属性上,绑定SelectedPerson到ListBox的SelectedItem属性上。
使用RelayCommand类实现命令,该类可以在WPF中重复使用,代码如下:
```csharp
public class RelayCommand : ICommand
{
private readonly Action _execute;
private readonly Func<bool> _canExecute;
public RelayCommand(Action execute)
: this(execute, null)
{
}
public RelayCommand(Action execute, Func<bool> canExecute)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute();
}
public void Execute(object parameter)
{
_execute();
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
```
阅读全文