在WPF(Windows Presentation Foundation)应用程序中,DataGrid
是一个常用的控件,用于显示和编辑数据。当需要显示一个包含字符串属性的类的 ObservableCollection
时,可以通过数据绑定来实现。以下是一些基础概念和相关信息:
ObservableCollection
的特性,当集合中的数据发生变化时,UI会自动更新。在这个场景中,我们通常会定义一个类,该类包含需要显示的字符串属性,然后将这个类的实例添加到 ObservableCollection
中。
假设我们有一个简单的 Person
类,包含 FirstName
和 LastName
属性:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
然后我们创建一个 ObservableCollection<Person>
并将其绑定到 DataGrid
:
<Window x:Class="YourNamespace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="800">
<Grid>
<DataGrid x:Name="personDataGrid" AutoGenerateColumns="True" />
</Grid>
</Window>
在代码后台:
using System.Collections.ObjectModel;
using System.Windows;
namespace YourNamespace
{
public partial class MainWindow : Window
{
public ObservableCollection<Person> People { get; set; }
public MainWindow()
{
InitializeComponent();
People = new ObservableCollection<Person>
{
new Person { FirstName = "John", LastName = "Doe" },
new Person { FirstName = "Jane", LastName = "Smith" }
};
personDataGrid.ItemsSource = People;
}
}
}
问题: DataGrid
没有显示任何数据。
原因: 可能是由于 ItemsSource
没有正确设置,或者数据集合为空。
解决方法: 确保 ItemsSource
已经被设置为 ObservableCollection
,并且集合中至少有一个元素。
问题: 数据更新后,UI没有自动刷新。
原因: 可能是由于 ObservableCollection
没有正确通知UI更新,或者属性没有实现 INotifyPropertyChanged
接口。
解决方法: 确保使用的是 ObservableCollection
,并且如果需要实时更新单个对象的属性,那么对象应该实现 INotifyPropertyChanged
接口。
public class Person : INotifyPropertyChanged
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
OnPropertyChanged(nameof(FirstName));
}
}
private string _lastName;
public string LastName
{
get { return _lastName; }
set
{
_lastName = value;
OnPropertyChanged(nameof(LastName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
通过以上步骤,你应该能够在 DataGrid
中成功显示并更新具有字符串属性的类的 ObservableCollection
。
云+社区技术沙龙[第17期]
云+社区技术沙龙[第19期]
腾讯技术开放日
腾讯位置服务技术沙龙
TC-Day
TC-Day
腾讯自动驾驶系列公开课
云+社区技术沙龙[第3期]
领取专属 10元无门槛券
手把手带您无忧上云