将列表框中的某些项绑定到combox项目源
我有一个包含很多项目的列表框,并且我在C#WPF中有一个组合框。将列表框中的某些项绑定到combox项目源
我想将combobox的itemsource绑定到listbox的itemsource,但我想过滤掉一些项目(这是一个xml数据源,我想过滤项目元素的某个元素的内容)。 实施例项:
<Item>
<itemtype>A</itemtype>
<itemname>Name</itemname>
</item>
<Item>
<itemtype>B</itemtype>
<itemname>Name</itemname>
</item>
我想的添加项目时到列表框但随后的项目的“姓名”值时,它在列表框被改变,不更新手动将项目添加到组合框。
这样做的好方法是什么?假设我只想显示带有itemtype B的所有项目名称。是否可以在wpf绑定中完成,还是需要在后面执行一些代码?
它是对数据源的引用,例如,如果您使用MVC模式,则将其添加到视图模型中的集合中。令人惊奇的是,它的使用非常简单。该视图被更新并具有它自己的刷新处理。我将做一个小例子:
在WPF:
<ListBox ItemsSource={Binding Path=MySource} ItemTemplate="{StaticResource myItemTemplate}" />
的代码逻辑:
public class Item
{
public string Name { get; set; }
public string Type { get; set; }
}
public class MyViewModel
{
public ObservableCollection<Item> MySource { get; set; }
public MyViewModel()
{
this.MySource = new ObservableCollection<Item>();
this.MySource.Add(new Item() { Name = "Item4", Type = "C" });
this.MySource.Add(new Item() { Name = "Item1", Type = "A" });
this.MySource.Add(new Item() { Name = "Item2", Type = "B" });
this.MySource.Add(new Item() { Name = "Item3", Type = "A" });
// get the viewsource
ListCollectionView view = (ListCollectionView)CollectionViewSource
.GetDefaultView(this.MySource);
// first of all sort by type ascending, and then by name descending
view.SortDescriptions.Add(new SortDescription("Type", ListSortDirection.Ascending));
view.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Descending));
// now i like to group the items by type
view.GroupDescriptions.Add(new PropertyGroupDescription("Type"));
// and finally i want to filter all items, which are of type C
// this is done with a Predicate<object>. True means, the item will
// be shown, false means not
view.Filter = (item) =>
{
Item i = item as Item;
if (i.Type != "C")
return true;
else
return false;
};
// if you need a refreshment of the view, because of some items were not updated
view.Refresh();
// if you want to edit a single item or more items and dont want to refresh,
// until all your edits are done you can use the Edit pattern of the view
Item itemToEdit = this.MySource.First();
view.EditItem(itemToEdit);
itemToEdit.Name = "Wonderfull item";
view.CommitEdit();
// of course Refresh/Edit only makes sense in methods/callbacks/setters not
// in this constructor
}
}
有趣的是,这种模式将直接影响到GUI列表框中。如果添加分组/排序,这将影响列表框的显示行为,即使itemssource只绑定到视图模型。
在这种情况下绑定的问题是,它只能设置一次。所以如果你绑定它,源是同步的。您可以使用转换器进行绑定,以过滤不想绑定的项目。另一种方法是使用WPF的精彩CollectionViewSource。
您可以在任何种类的ItemsSource上将分组/排序和过滤器添加到CollectionViewSource。例如,使用ListCollectionView。
ListCollectionView view =
(ListCollectionView)CollectionViewSource.GetDefaultView(yourEnumerableSource);
所以'yourEnumerableSource'是对列表框还是对数据源的引用?当数据源发生变化时,更新的视图是? – internetmw 2010-08-20 23:30:00
看到第二个帖子 – JanW 2010-08-21 08:54:26
感谢您的详细解释。那么如何将我当前的数据源设置为observablecollection? 所以根据你的解释我过滤该集合。我是否将集合绑定到代码或xaml中的组合框? – internetmw 2010-08-21 22:56:11
这是非常有益的,谢谢! – 2011-05-05 22:01:00