c# - 当我实现 MVVM 时,如何更新 WPF 数据网格中的一行? (没有任何按钮)

标签 c# wpf mvvm

我已经制作了一个没有 MVVM 的 WPF 应用程序,并且我确实通过使用诸如 CellEditEnding 之类的事件来更新我的行,但是现在我想在 MVVM 中做同样的事情,所以我不打算使用任何事件,我应该这样做我的 View 模型。

我该怎么做? (我喜欢一种只更新已更改的行的方法)。我想使用 Datagrid 的功能而不是使用任何按钮,例如更新按钮。

  • 顺便说一句,当我完成它时,我会选择完整的 CRUD 系统。
  • 最佳答案

    我在 WPF 和 MVVM 中看到的最大的“事情”是数据绑定(bind)。因此,您不必告诉 GUI 确切地做什么(即 CellEditEnding 等),而是将编辑留给 GUI( View )并只处理 Viewmodel 中的数据。

    正如您在下面的示例中所见(它非常简单),没有关于如何执行更新单元格等操作的代码,只有一个数据绑定(bind) - 将 ObservableCollection 绑定(bind)到 DataGrid 的 ItemsSource

    例子:

    <Window x:Class="WpfApplication12.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:WpfApplication12="clr-namespace:WpfApplication12"
            Title="MainWindow" Height="350" Width="525">
        <Window.DataContext>
            <WpfApplication12:MainWindowViewModel />
        </Window.DataContext>
        <Grid>
            <DataGrid ItemsSource="{Binding PersonList}">
    
            </DataGrid>
        </Grid>
    </Window>
    

    C#代码隐藏:
    public class MainWindowViewModel : INotifyPropertyChanged
    {
        public MainWindowViewModel()
        {
            PersonList = new ObservableCollection<Person>()
                             {
                                 new Person(){Name="Bobby"}
                              };
        }
        public ObservableCollection<Person> PersonList { get; set; }
        public void OnPropertyChanged(string p)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(p));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
    public class Person : INotifyPropertyChanged
    {
        private string name;
    
        public string Name
        {
            get { return name; }
            set
            {
                if (name != value)
                {
                   name = value;
                   OnPropertyChanged("Name");
                 }
           }
        }
        public void OnPropertyChanged(string p)
        {
           if (PropertyChanged != null)
           {
               PropertyChanged(this, new PropertyChangedEventArgs(p));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
    

    正如我之前所说,这很简单,只是为了让你开始。

    关于c# - 当我实现 MVVM 时,如何更新 WPF 数据网格中的一行? (没有任何按钮),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5296941/

    相关文章:

    c# - 在 C# 中处理指定的成员类

    wpf - 如何使用冒号设置标签样式

    c# - 更改 XAML 中的绑定(bind)值

    wpf - 使用 mvvm 的可编辑 ComboBox 设置插入符位置

    wpf - MvvmLight-在DataGrid中隐藏IsInDesignMode

    c# - 在 checkin 和未决更改窗口中获取选定的文件?

    c# - Entity Framework 排序列表<MyClass>

    wpf - UserControl- WPF中的Click事件

    c# - 将集合绑定(bind)到 Ninject

    c# - 类型名称后的符号 '?' 是什么意思