简体   繁体   English

我的ListBox ItemSource如何在WPF和C#中实现可观察的集合

[英]How can my ListBox ItemSource implement an observable collection in WPF and C#

I have a ListBox (EmpView) which is populated by a select statement via LINQ to SQL from a typed dataset. 我有一个ListBox (EmpView),该ListBox由一个SELECT语句通过LINQ to SQL从类型化数据集中填充。 I have to put a button to be able to refresh the list box with updated data. 我必须按下一个按钮才能刷新具有更新数据的列表框。

How do I make my dataset (if possible) or get my ListBox ItemSource to implement an observable collection? 如何制作数据集(如果可能)或获取ListBox ItemSource来实现可观察的集合?

Here is my code 这是我的代码

public partial class ListOfEmployees : UserControl
{
    MyDataContext db = new MyDataContext();

    var employees = from emp in db.EmployeeMasters
    orderby emp.Surname
    select emp;         

    EmpView.ItemsSource = employees;
}

All you should need to do then is create a new ObservableCollection with the selected items added via the constrctor or Add . 然后,您需要做的就是创建一个新的ObservableCollection ,并通过constrctor或Add选定的项。 eg 例如

var observableCollection = new ObservableCollection<Employee>(employees);
EmpView.ItemsSource = observableCollection;

The type of your item class may of course be different. 您的商品类别的类型当然可能有所不同。 To easily change the collection you might want to store a reference to it somewhere. 为了轻松更改集合,您可能需要将对其的引用存储在某个地方。

As noted in the comments this will only take note of changes caused by explicit operations on the collection. 如评论中所述,这仅会注意由对集合的显式操作引起的更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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