在 WPF(Windows Presentation Foundation)中,你可以使用 C# 提供的各种字典集合来存储键值对数据(类似于其他语言中的 “Map”)。WPF 本身不提供特殊的 “Map” 类型,但可以通过以下方式定义和使用集合:
- 使用 Dictionary<TKey, TValue>(最常用)
Dictionary 是 C# 中最常用的键值对集合,支持快速查找。
using System.Collections.Generic;
// 定义一个字典,键为string,值为int
Dictionary<string, int> scoreMap = new Dictionary<string, int>
{
{ "Alice", 90 },
{ "Bob", 85 },
{ "Charlie", 95 }
};
// 添加元素
scoreMap["David"] = 88;
// 访问元素
int aliceScore = scoreMap["Alice"]; // 90
// 安全访问(避免KeyNotFoundException)
if (scoreMap.TryGetValue("Eve", out int eveScore))
{
// 存在键 "Eve"
}
else
{
// 不存在
}
- 使用 ObservableCollection<KeyValuePair<TKey, TValue>>(用于数据绑定)
如果需要在 XAML 中绑定字典数据,Dictionary 本身不支持动态通知,建议使用 ObservableCollection<KeyValuePair<TKey, TValue>>:
using System.Collections.Generic;
using System.Collections.ObjectModel;
// 定义可观察的键值对集合
ObservableCollection<KeyValuePair<string, int>> scoreCollection =
new ObservableCollection<KeyValuePair<string, int>>
{
new KeyValuePair<string, int>("Alice", 90),
new KeyValuePair<string, int>("Bob", 85)
};
// 添加元素(自动触发UI更新)
scoreCollection.Add(new KeyValuePair<string, int>("Charlie", 95));
XAML 绑定示例:
<ListBox ItemsSource="{Binding ScoreCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Key}" Margin="5"/>
<TextBlock Text="{Binding Value}" Margin="5"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
- 使用 ConcurrentDictionary<TKey, TValue>(线程安全)
在多线程环境中,使用 ConcurrentDictionary 保证线程安全:
using System.Collections.Concurrent;
ConcurrentDictionary<string, int> concurrentScoreMap = new ConcurrentDictionary<string, int>();
// 线程安全地添加或更新
concurrentScoreMap.AddOrUpdate("Alice", 90, (key, oldValue) => oldValue + 5);
// 线程安全地获取
if (concurrentScoreMap.TryGetValue("Alice", out int score))
{
// 使用 score
}
- 自定义字典类(实现 INotifyPropertyChanged)
如果需要字典本身支持属性变更通知(如添加 / 删除元素时通知 UI),可以自定义类:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
public class ObservableDictionary<TKey, TValue> : ObservableCollection<KeyValuePair<TKey, TValue>>
{
public void Add(TKey key, TValue value)
{
Add(new KeyValuePair<TKey, TValue>(key, value));
}
public TValue this[TKey key]
{
get
{
foreach (var item in Items)
{
if (EqualityComparer<TKey>.Default.Equals(item.Key, key))
{
return item.Value;
}
}
throw new KeyNotFoundException();
}
set
{
for (int i = 0; i < Items.Count; i++)
{
if (EqualityComparer<TKey>.Default.Equals(Items[i].Key, key))
{
SetItem(i, new KeyValuePair<TKey, TValue>(key, value));
return;
}
}
Add(key, value);
}
}
}
使用示例:
ObservableDictionary<string, int> observableMap = new ObservableDictionary<string, int>();
observableMap["Alice"] = 90; // 自动触发UI更新
- 其他字典类型
- SortedDictionary<TKey, TValue>:按键排序的字典。
- SortedList<TKey, TValue>:按键排序的列表,内存效率更高。
- HybridDictionary:在元素少时使用List,元素多时自动转为Hashtable(需引System.Collections.Specialized)。
选择建议
常规场景:使用 Dictionary<TKey, TValue>。
数据绑定:使用 ObservableCollection<KeyValuePair<TKey, TValue>> 或自定义 ObservableDictionary。
多线程:使用 ConcurrentDictionary<TKey, TValue>。
需要排序:使用 SortedDictionary<TKey, TValue> 或 SortedList<TKey, TValue>。
示例:在 ViewModel 中使用字典绑定到 UI
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
// 使用ObservableCollection绑定字典数据
public ObservableCollection<KeyValuePair<string, int>> ScoreCollection { get; set; }
= new ObservableCollection<KeyValuePair<string, int>>();
public ViewModel()
{
// 初始化数据
ScoreCollection.Add(new KeyValuePair<string, int>("Alice", 90));
ScoreCollection.Add(new KeyValuePair<string, int>("Bob", 85));
}
// 添加新分数的方法
public void AddScore(string name, int score)
{
ScoreCollection.Add(new KeyValuePair<string, int>(name, score));
OnPropertyChanged(nameof(ScoreCollection));
}
}
459

被折叠的 条评论
为什么被折叠?



