简体   繁体   中英

How can I make an editable DataGrid in WPF?

Basically I have the following in my MainWindow:

public ObservableCollection<KeyValuePair<string, int>> Environment { get; set; }

and I want to bind it to a datagrid in such a way that I can edit the data grid and have Environment be updated. Specifically, I want to be able to add new rows, delete rows, and edit individual cells. How can I do this?

In xaml you can write:

<DataGrid ItemsSource="{Binding}">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="SomeString">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding SomeString}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="SomeInt>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding SomeInt}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

In code behind make: Data class "DataClass" with fields SomeString and SomeInt "ViewModel" class, inherits INotifyPropertyChanged and use "DataClass" Write:

 ObservableCollection<ViewModel> Environment

and instatiate it with pairs of SomeString and SomeInt

Set datacontext of control with DataGrid Environment:

    MyUserControl.DataContext =  Environment;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM