我本以为这个问题已经得到了答案,但我没有找到。我有一个简单的类:
public class BinanceEndpoint : ObservableObject
{
private string baseAddress;
private string socketBaseAddress;
public string BaseAddress
{
get { return baseAddress; }
set { baseAddress = value; RaisePropertyChangedEvent(nameof(BaseAddress)); }
}
public string SocketBaseAddress
{
get { return socketBaseAddress; }
set { socketBaseAddress = value; RaisePropertyChangedEvent(nameof(SocketBaseAddress)); }
}
}
然后,我用这个类的对象填充ObservableDictionary:
private MainViewModel()
{
private BinanceEndpoint apiEndPoint;
private ObservableDictionary<string, BinanceEndpoint> endPoints = new ObservableDictionary<string, BinanceEndpoint>();
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", });
}
[JsonIgnore]
public ObservableDictionary<string,BinanceEndpoint> EndPoints
{
get { return endPoints; }
set { endPoints = value; RaisePropertyChangedEvent(nameof(EndPoints)); }
}
public BinanceEndpoint APIEndPoint
{
get { return apiEndPoint; }
set { apiEndPoint = value; RaisePropertyChangedEvent(nameof(APIEndPoint)); }
}
}
然后我尝试使用ObservableDictionary来填充ComboBox。
<ComboBox Grid.Column="1" ItemsSource="{Binding EndPoints}" DisplayMemberPath="Key" SelectedValuePath="Value" SelectedValue="{Binding Path=APIEndPoint, Mode=TwoWay}"/>
我遇到的问题是SelectedValue在加载时不会更新组合框的值。我做错了什么?
首先应该避免绑定到Dictionary
。.NET库中没有ObservableDictionary是有原因的——自2002年发布以来。我想我们同意这并不是因为MS开发人员这么多年后不知道如何实现这样一个字典。
您的SelectedValuePath
和SelectedValue
使用错误。SelectedValue
返回SelectedValuePath
所指向的属性的值。SelectedValuePath
提供了SelectedItem
上的属性路径
当您主动设置SelectedValue
时,控件将尝试查找并选择SelectedValuePath
指定的项目属性与SelectedValue
值匹配的项目。
当SelectedItem
返回所选项目(实例)时,则SelectedValue
返回使用SelectedValuePath
指定的该SelectedItem
上的属性的值。
例如:我们绑定到一个Dictionary<string, BinanceEndpoint>
。要显示Dictionary
的Key
,我们指定DisplayMemberPath
(作为DataTemplate
的替代方案)SelectedItem
将保存KeyValuePair<string, BinanceEndpoint>
要使ComboBox.SelectedValue
返回所选项目的SocketBaseAddress
值,我们必须将SelectedValuePath
设置为"Value.SocketBaseAddress"
:
<ComboBox x:Name="ComboBox"
ItemsSource="{Binding EndPoints}"
DisplayMemberPath="Key"
SelectedValuePath="Value.SocketBaseAddress" />
<!-- Display the selected item's SocketBaseAddress value -->
<TextBlock text="{Binding ElementName=ComboBox, Path=SelectedValue}" />
如果希望SelectedValue
返回BinanceEndpoint
实例,则将SelectedValuePath
设置为"Value"
:
<ComboBox x:Name="ComboBox"
ItemsSource="{Binding EndPoints}"
DisplayMemberPath="Key"
SelectedValuePath="Value" />
<!-- Display the selected item's 'SocketBaseAddress' value -->
<TextBlock text="{Binding ElementName=ComboBox, Path=SelectedValue.SocketBaseAddress}" />