在WPF中,可以通过以下步骤向ObservableCollection添加数据:
<ListView ItemsSource="{Binding MyCollection}">
<!-- 定义ListView的列 -->
<ListView.View>
<GridView>
<GridViewColumn Header="姓名" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="年龄" DisplayMemberBinding="{Binding Age}" />
</GridView>
</ListView.View>
</ListView>
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class MainViewModel : INotifyPropertyChanged
{
private ObservableCollection<Person> myCollection;
public ObservableCollection<Person> MyCollection
{
get { return myCollection; }
set
{
myCollection = value;
OnPropertyChanged(nameof(MyCollection));
}
}
public MainViewModel()
{
MyCollection = new ObservableCollection<Person>();
}
// 添加数据的方法
public void AddData()
{
MyCollection.Add(new Person { Name = "John", Age = 25 });
MyCollection.Add(new Person { Name = "Alice", Age = 30 });
}
// INotifyPropertyChanged接口的实现
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
MainViewModel viewModel = new MainViewModel();
viewModel.AddData();
这样,当AddData方法被调用时,ObservableCollection中的数据会自动更新,并且XAML中的控件会自动刷新显示新添加的数据。
推荐的腾讯云相关产品:腾讯云云服务器(CVM)和腾讯云数据库(TencentDB)。
领取专属 10元无门槛券
手把手带您无忧上云