如何使用 mvvm 在 wpf 中制作可编辑的数据网格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19649546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 23:59:25  来源:igfitidea点击:

How to do editable data grid in wpf using mvvm?

wpfmvvmdatagrid

提问by SNS

I want to use a editable data grid, to add, edit data. Is it possible with wpf? Can some one give an the example?

我想使用可编辑的数据网格来添加、编辑数据。wpf可以吗?有人可以举个例子吗?

回答by Omri Btian

DataGridcontrols has all that functionality built-in. You can set the properties CanUserAddRowsto true to allow user to add rows.

DataGrid控件具有内置的所有功能。您可以将属性CanUserAddRows设置为 true 以允许用户添加行。

DataGridis editable by default, where each column has an edit control which lets you edit its value. By default the DataGridautomatically generates columns for every property in your Model, so you don't even have to define it's columns.

DataGrid默认情况下是可编辑的,其中每列都有一个编辑控件,可让您编辑其值。默认情况下,会DataGridModel 中的每个属性自动生成列,因此您甚至不必定义它的列。

Here are some good links with detailed examples you can look into:

以下是一些很好的链接,其中包含您可以查看的详细示例:

http://wpftutorial.net/DataGrid.html

http://wpftutorial.net/DataGrid.html

http://www.codeproject.com/Articles/30905/WPF-DataGrid-Practical-Examples

http://www.codeproject.com/Articles/30905/WPF-DataGrid-Practical-Examples

http://www.c-sharpcorner.com/UploadFile/mahesh/datagrid-in-wpf/

http://www.c-sharpcorner.com/UploadFile/mahesh/datagrid-in-wpf/

Good luck

祝你好运

回答by Kumareshan

Have a Xaml as below

有一个 Xaml 如下

<Window x:Class="DatGrid.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"
    xmlns:local="clr-namespace:DatGrid">
<Window.DataContext>
    <local:ViewModel/>
</Window.DataContext>
<StackPanel/>
    <DataGrid ItemsSource="{Binding Path=Values}"></DataGrid>
</StackPanel>
</Window>

In the ViewModel is very simple some thing like below

在 ViewModel 中非常简单,如下所示

class ViewModel
{
    public ObservableCollection<Example> Values
    {
        get;
        set;
    }
}
public class Example
{
    public string A
    {
        get;
        set;
    }
    public string B
    {
        get;
        set;
    }
}

In the view you can always see a empty row you can just click and type something and press enter it'll get updated to the ViewModel

在视图中,您始终可以看到一个空行,您只需单击并输入内容并按 Enter 键它就会更新到 ViewModel