[英]WPF binding ObservableCollection with converter
我有一個 ObservableCollection 字符串,我想將它與轉換器綁定到 ListBox 並僅顯示以某些前綴開頭的字符串。
我寫:
public ObservableCollection<string> Names { get; set; }
public MainWindow()
{
InitializeComponent();
Names= new ObservableCollection<Names>();
DataContext = this;
}
和轉換器:
class NamesListConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return null;
return (value as ICollection<string>).Where((x) => x.StartsWith("A"));
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
和 XAML:
<ListBox x:Name="filesList" ItemsSource="{Binding Path=Names, Converter={StaticResource NamesListConverter}}" />
但是列表框在更新(添加或刪除)后不會更新。
我注意到,如果我從綁定中刪除轉換器,它的工作原理是完美的。 我的代碼有什么問題?
您的轉換器正在從原始 ObservableCollection 中的對象創建新集合。 使用您的綁定設置的 ItemsSource 不再是原始 ObservableCollection。 為了更好地理解,這等於你寫的:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return null;
var list = (value as ICollection<string>).Where((x) => x.StartsWith("A")).ToList();
return list;
}
轉換器返回的列表是帶有源集合中數據副本的新對象。 原始集合中的進一步更改不會反映在該新列表中,因此 ListBox 不知道該更改。 如果要過濾數據,請查看CollectionViewSource 。
編輯:如何過濾
public ObservableCollection<string> Names { get; set; }
public ICollectionView View { get; set; }
public MainWindow()
{
InitializeComponent();
Names= new ObservableCollection<string>();
var viewSource = new CollectionViewSource();
viewSource.Source=Names;
//Get the ICollectionView and set Filter
View = viewSource.View;
//Filter predicat, only items that start with "A"
View.Filter = o => o.ToString().StartsWith("A");
DataContext=this;
}
在 XAML 中將 ItemsSource 設置為 CollectionView
<ListBox x:Name="filesList" ItemsSource="{Binding Path=View}"/>
添加或刪除元素時,可能沒有使用轉換器。 實現您想要的最簡單方法可能是在您的類中實現 INotifyPropertyChanged 並在每次添加或刪除項目時觸發 PropertyChanged 事件。 一般來說,“正確”的方法是使用CollectionView
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.