datagrid列改变值其他列未变
时间: 2023-09-19 16:11:44 浏览: 49
你好!感谢您的提问。您的问题有些不太清晰,我理解您的意思是当您在 DataGrid 中更改某一列的值时,其他列的值没有更新。这可能是因为您没有正确地绑定 DataGrid 的数据源。在 WPF 中,您需要使用 INotifyPropertyChanged 接口来通知 DataGrid 中数据的更改。以下是一个示例:
首先,在您的 ViewModel 中实现 INotifyPropertyChanged 接口,并在属性更改时引发 PropertyChanged 事件:
```csharp
public class MyViewModel : INotifyPropertyChanged
{
private string _name;
private int _age;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged(nameof(Name));
}
}
public int Age
{
get { return _age; }
set
{
_age = value;
OnPropertyChanged(nameof(Age));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
```
然后,您需要将 DataGrid 的 ItemsSource 属性绑定到 ViewModel 中的一个可枚举集合:
```xaml
<DataGrid ItemsSource="{Binding MyItems}" />
```
最后,确保在 ViewModel 中初始化 MyItems 集合,并将 DataGrid 中的列绑定到 ViewModel 的属性:
```csharp
public class MyViewModel : INotifyPropertyChanged
{
public ObservableCollection<MyItem> MyItems { get; } = new ObservableCollection<MyItem>
{
new MyItem { Name = "Alice", Age = 25 },
new MyItem { Name = "Bob", Age = 30 },
new MyItem { Name = "Charlie", Age = 35 }
};
}
public class MyItem : INotifyPropertyChanged
{
private string _name;
private int _age;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged(nameof(Name));
}
}
public int Age
{
get { return _age; }
set
{
_age = value;
OnPropertyChanged(nameof(Age));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
```
现在,当您更改 DataGrid 中的任何一列时,所有列的值都应该会更新。希望这可以帮到您!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)