gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:40:26 25 4
gpt4 key购买 nike

我已经制作了一个没有 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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com