
AI
使用键(如字典)实现 ObservableCollection
csharppublic class ObservableDictionary<K, T> : ObservableCollection<KeyValuePAIr<K, T>>{ private Dictionary<K, T> _dictionary = new Dictionary<K, T>(); protected override void ClearItems() { _dictionary.Clear(); base.ClearItems(); } protected override void InsertItem(int index, KeyValuePAIr<K, T> item) { _dictionary[item.Key] = item.Value; base.InsertItem(index, item); } protected override void RemoveItem(int index) { K key = this[index].Key; _dictionary.Remove(key); base.RemoveItem(index); } protected override void SetItem(int index, KeyValuePAIr<K, T> item) { K key = this[index].Key; _dictionary.Remove(key); _dictionary[item.Key] = item.Value; base.SetItem(index, item); } public T this[K key] { get { return _dictionary[key]; } set { if (_dictionary.ContAInsKey(key)) { int index = Items.IndexOf(Items.FirstOrDefault(i => i.Key.Equals(key))); Items[index] = new KeyValuePAIr<K, T>(key, value); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, Items[index], Items[index], index)); } else { Add(new KeyValuePAIr<K, T>(key, value)); } } }}使用自定义的ObservableDictionary使用自定义的ObservableDictionary与使用普通的ObservableCollection类似。我们可以在XAML中定义一个ItemsControl,然后将ObservableDictionary作为其ItemsSource进行绑定。这样,当ObservableDictionary中的数据发生变化时,ItemsControl中的UI元素会自动进行更新。下面是一个简单的例子,演示如何使用自定义的ObservableDictionary:xaml<Window x:Class="WpfApp.MAInWindow"</p> XMLns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" XMLns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MAInWindow" Height="450" Width="800"> <Grid> <ItemsControl ItemsSource="{Binding MyDictionary}"> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Key}" Margin="5"/> <TextBlock Text="{Binding Value}" Margin="5"/> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Grid></Window>csharppublic partial class MAInWindow : Window{ public ObservableDictionary<string, int> MyDictionary { get; set; } public MAInWindow() { InitializeComponent(); MyDictionary = new ObservableDictionary<string, int>(); MyDictionary.Add("Apple", 5); MyDictionary.Add("Banana", 3); MyDictionary.Add("Orange", 7); DataContext = this; }}在上面的例子中,我们创建了一个ObservableDictionary,其键为字符串类型,值为整数类型。然后,我们向ObservableDictionary中添加了几个键值对,并将其绑定到一个ItemsControl中进行展示。当ObservableDictionary中的数据发生变化时,ItemsControl中的UI元素会自动更新。通过使用键(如字典)实现自定义的ObservableCollectionCopyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号