WPF MVVM中如何通过命令重置PropertyGrid数据并刷新绑定
WPF MVVM下通过命令实现PropertyGrid数据还原
步骤1:给复用的用户控件uc1添加命令依赖属性
因为uc1要在多个视图中复用,需通过依赖属性传递Cancel命令,让每个父视图可绑定自身ViewModel的命令逻辑:
public partial class uc1 : UserControl { public static readonly DependencyProperty CancelCommandProperty = DependencyProperty.Register(nameof(CancelCommand), typeof(ICommand), typeof(uc1)); public ICommand CancelCommand { get => (ICommand)GetValue(CancelCommandProperty); set => SetValue(CancelCommandProperty, value); } public uc1() { InitializeComponent(); } }
在uc1的XAML中,将Cancel按钮的Command绑定到该依赖属性:
<Button Content="Cancel" Command="{Binding CancelCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" />
步骤2:ViewModel中实现Cancel命令与数据还原逻辑
假设ViewModel已实现INotifyPropertyChanged,且有绑定PropertyGrid的属性(如CurrentEditableObject),同时保存了原始数据副本(如OriginalObject):
定义Cancel命令
用RelayCommand(或自定义DelegateCommand)实现命令:
public ICommand CancelCommand { get; } public YourViewModel() { CancelCommand = new RelayCommand(ExecuteCancel); // 初始化时保存原始数据独立副本 OriginalObject = DeepCopy(CurrentEditableObject); }
实现命令执行逻辑
在执行方法中调用已有还原方法,再通过重新赋值绑定属性触发PropertyGrid刷新:
private void ExecuteCancel() { // 调用已实现的还原方法 RevertToOriginalData(); // 先清空绑定再重新赋值,模拟后台代码的清空+重绑效果 CurrentEditableObject = null; CurrentEditableObject = OriginalObject; // 如果RevertToOriginalData是直接修改CurrentEditableObject的属性,只需触发变更通知: // OnPropertyChanged(nameof(CurrentEditableObject)); } // 确保绑定属性实现INotifyPropertyChanged private object _currentEditableObject; public object CurrentEditableObject { get => _currentEditableObject; set { _currentEditableObject = value; OnPropertyChanged(); } } private object OriginalObject { get; set; }
注:DeepCopy需自行实现(如序列化或手动复制属性),用于保存原始数据的独立副本,避免还原时影响已修改的数据。
步骤3:在父视图中绑定命令
使用uc1时,直接将其CancelCommand绑定到父ViewModel的CancelCommand:
<local:uc1 CancelCommand="{Binding CancelCommand}" />
关键说明
核心逻辑是通过数据绑定而非直接操作控件实现UI刷新:PropertyGrid的SelectedObject(或对应绑定属性)会随ViewModel中属性的变化自动更新,无需手动清空容器;若使用第三方PropertyGrid控件(如DevExpress),只需确保绑定属性的变更通知正常触发,控件会自动响应数据变化。
内容的提问来源于stack exchange,提问作者user2137622
相关产品推荐
相关产品推荐

