我已经看过一些使用colllectionView进行排序和过滤的例子,但没有一个以比较逻辑的方式做。
示例:
// Button event to send an item from LB1 to LB2
private void BaddProduct_Click(object sender, RoutedEventArgs e)
{
if(Lb2.Items.Contains("item"))
{
MessageBox.Show("This item is already there!");
}
//second example
if(Lb2.Items.StartWith("item"))
{
MessageBox.Show("This item is already there!");
}
}
该代码适用于winforms。是否有WPF的方法?
谢谢!
答案 0 :(得分:0)
此代码也适用于.xaml.cs文件,作为'背后的代码。直接引用所有已命名的非模板WPF项目。
如果您希望数据源更加动态,我建议使用IEnumerable集合将ItemSource绑定到,然后您可以使用LINQ执行所有过滤。
(编辑:修复拼写错误'数据源'到数据源')
答案 1 :(得分:0)
对于任何需要这种方法的人:
//called by the collectionView
private bool UserFilter(object item)
{
string produtoItem;
//my LB1. With dynamic type i am gettting the item selected.
dynamic selectProdutoItem = LbProdutoPlano.SelectedItem;
produtoItem = selectProdutoItem.produtoPlanoNome;
if (String.IsNullOrEmpty(produtoItem))
{
return true;
}
else
{
//this will do a comparative logic on my selected item on LB 1. fichaProduto is my class and fichaProdutoProdutoNome a string of that class that is the same string or the item in LB1, produtoItem.
return ((item as fichaProduto).fichaProdutoProdutoNome.IndexOf(produtoItem, StringComparison.OrdinalIgnoreCase) >= 0);
}
}
// a button to add an item from LB1 to LB2.
private ButtonAdd_Click()
{
//created the collectionView in here having the itemSource the LB2 that is already binded.
CollectionView viewFiltro = (CollectionView)CollectionViewSource.GetDefaultView(LbProdutoPlanoEscolhido.ItemsSource);
// this is the key of this logic. The View will do a comparative logic from the retur of the UserFilter method.
viewFiltro.Filter = UserFilter;
// so if the View found it, it will count 1.
if (viewFiltro.Count == 1)
{
MessageBox.Show("This product is already in the LB2.");
}
else
{
// add the item into LB 2.
}
}
通过这种方式,我们不必为任何ListBox都比较observable的Collection。只需使用CView的谓词过滤器,并使用属性COUNT检查它的结果。如果为1,则表示过滤器搜索LB1中的项目并在LB 2上找到它。