繁体   English   中英

如何将WPF ListBox项目与字符串进行比较?

[英]How to compare WPF ListBox Items with a String?

我已经看到了一些使用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有办法吗?

谢谢!

该代码也可以在.xaml.cs文件中使用,因为“后面的代码”直接引用了所有已命名的非模板WPF项。

如果您希望数据源更具动态性,建议您使用IEnumerable集合将ItemSource绑定到其中,然后可以使用LINQ执行所有筛选。

(编辑:错别字'数据源'固定为'数据源')

对于需要这种方法的任何人:

//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. 
         }
}

这样,我们就不必为列表框中的任何一个都比较observable´s Collection。 只需使用CView的谓词Filter并使用COUNT属性检查其结果。 如果为1,则表示LB1中某项的过滤器搜索已在LB 2上找到。

暂无
暂无

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

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