You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF绑定ObservableDictionary到ComboBox时SelectedValue加载不更新如何解决

问题1:私有字段定义位置错误(最高概率)

你当前把apiEndPoint和endPoints两个私有字段的声明写在了MainViewModel的构造函数内部,C#中构造函数内声明的变量是局部变量,仅在构造函数执行期间有效,和类属性EndPoints、APIEndPoint所访问的类级别私有字段完全无关。这就导致你绑定的EndPoints属性实际指向的类字段根本没有被初始化,要么为null要么是空集合,SelectedValue自然无法匹配到选中项。

修正方式:把两个私有字段的声明移到构造函数外部,作为类的成员:

// 移到构造函数外,作为类的私有字段
private BinanceEndpoint apiEndPoint;
private ObservableDictionary<string, BinanceEndpoint> endPoints = new ObservableDictionary<string, BinanceEndpoint>();

private MainViewModel()
{
    // 构造函数内仅做集合填充和初始值赋值
    endPoints.Add("Binance.com", new BinanceEndpoint() { BaseAddress = "https://api.binance.com", SocketBaseAddress = "wss://stream.binance.com:9443", });
    endPoints.Add("Binance.us", new BinanceEndpoint() { BaseAddress = "https://api.binance.us", SocketBaseAddress = "wss://stream.binance.us:9443", });
    endPoints.Add("Testnet", new BinanceEndpoint() { BaseAddress = "https://testnet.binance.vision", SocketBaseAddress = "wss://testnet.binance.vision", });
    
    // 记得给APIEndPoint赋初始值
    APIEndPoint = endPoints["Binance.com"];
}

问题2:未给APIEndPoint赋初始值

如果字段位置修正后还是有问题,检查你是否在页面加载前给APIEndPoint赋了有效值。如果APIEndPoint默认是null,ComboBox自然不会有默认选中项。你需要在构造函数填充完endPoints后,给APIEndPoint赋值为集合中的某一个BinanceEndpoint实例,如上面修正代码里的最后一行。

问题3:引用匹配失败(极低概率)

如果你给APIEndPoint赋值的实例不是EndPoints集合里的实例,而是自己重新new的BinanceEndpoint对象,哪怕两个对象的所有属性值完全一致,ComboBox默认按引用匹配也会认为两个对象不相等,不会选中对应项。这种情况要么你直接用集合里的实例给APIEndPoint赋值,要么给BinanceEndpoint类重写Equals和GetHashCode方法,按属性值判断相等。

内容的提问来源于stack exchange,提问作者Tyler Moore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 17:24:02