wpf datagrid双向绑定
时间: 2023-06-23 10:51:47 浏览: 82
WPF DataGrid 双向绑定可以通过使用 Binding 实现。下面是一个简单的示例:
1. 在 XAML 中定义一个 DataGrid 控件,设置 ItemsSource 属性绑定到 ViewModel 中的集合。
```xml
<DataGrid ItemsSource="{Binding Items}" />
```
2. 在 ViewModel 中定义一个 ObservableCollection 属性作为集合,用于存储 DataGrid 中的数据。
```csharp
public ObservableCollection<MyItem> Items { get; set; }
```
3. 在 MyItem 类中定义属性,用于绑定到 DataGrid 的列。
```csharp
public class MyItem
{
public string Name { get; set; }
public int Age { get; set; }
}
```
4. 在 XAML 中定义 DataGrid 的列,并将列的 Binding 属性绑定到对应的 MyItem 属性。
```xml
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />
<DataGridTextColumn Header="Age" Binding="{Binding Age}" />
```
这样就完成了 DataGrid 的双向绑定。当在 DataGrid 中编辑了数据时,ViewModel 中的集合也会相应地更新。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)