[英]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.