wpf mvvm demo
时间: 2025-03-27 22:49:00 浏览: 22
### WPF 使用 MVVM 模式的演示示例
#### 创建视图模型 (ViewModel)
为了展示如何在 WPF 中应用 MVVM 模式,可以创建一个简单的应用程序来管理待办事项列表。此例子将包括三个主要部分:Model、View 和 ViewModel。
##### 定义数据模型 (Model)
定义 `TodoItem` 类作为数据模型:
```csharp
public class TodoItem : INotifyPropertyChanged
{
private string _title;
public string Title
{
get { return _title; }
set
{
if (_title != value)
{
_title = value;
OnPropertyChanged(nameof(Title));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
```
##### 实现命令类 (Command Class)
实现用于处理 UI 命令的辅助类 `RelayCommand`:
```csharp
public class RelayCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Predicate<object> _canExecute;
public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute;
}
public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);
public void Execute(object parameter) => _execute(parameter);
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
```
##### 构建视图模型 (ViewModel)
构建 `MainViewModel`, 这里包含了业务逻辑以及与 View 的交互方法:
```csharp
public class MainViewModel : INotifyPropertyChanged
{
private ObservableCollection<TodoItem> _todoItems;
private TodoItem _selectedItem;
public ObservableCollection<TodoItem> TodoItems
{
get { return _todoItems; }
set
{
if (_todoItems != value)
{
_todoItems = value;
OnPropertyChanged(nameof(TodoItems));
}
}
}
public TodoItem SelectedItem
{
get { return _selectedItem; }
set
{
if (_selectedItem != value)
{
_selectedItem = value;
OnPropertyChanged(nameof(SelectedItem));
}
}
}
public ICommand AddNewItemCommand { get; }
public ICommand RemoveSelectedCommand { get; }
public MainViewModel()
{
TodoItems = new ObservableCollection<TodoItem>();
AddNewItemCommand = new RelayCommand(param =>
{
var newItem = new TodoItem();
TodoItems.Add(newItem);
SelectedItem = newItem;
});
RemoveSelectedCommand = new RelayCommand(
param => TodoItems.Remove(SelectedItem),
param => SelectedItem != null
);
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
```
#### 设计用户界面 (XAML)
最后,在 XAML 文件中绑定这些属性到控件上:
```xml
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<!-- ListView 绑定到 TodoItems -->
<ListView ItemsSource="{Binding TodoItems}"
SelectedItem="{Binding SelectedItem}">
<ListView.View>
<GridView>
<GridViewColumn Header="Task" DisplayMemberBinding="{Binding Title}"/>
</GridView>
</ListView.View>
</ListView>
<!-- 添加按钮 -->
<Button Content="Add New Task" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="100"
Command="{Binding AddNewItemCommand}" />
<!-- 删除选中的任务按钮 -->
<Button Content="Remove Selected" HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="100"
Command="{Binding RemoveSelectedCommand}" />
</Grid>
</Window>
```
通过这种方式,实现了基于 MVVM 模式的简单待办事项管理器[^1]。
阅读全文
相关推荐














