我有数据绑定(bind)问题。我有一个 WPF (MVVM) 用户控制项目。有Comboboxes
和 Labels
.每个ComboBox
绑定(bind)到 ObservableDictionary<int,string>
.所以我的问题是我只需要在 ComboBox
上显示字典的字符串部分.
另外,Combobox ItemSource
更改取决于之前选择的内容 ComboBox
.这也是 MVVM 模式。有模型和 View 模型。
我尝试设置 DisplayPath
等等,但我不能只显示组合上的字符串。总是看到 [0, sample]
, [1,yes]
.
<ComboBox HorizontalAlignment="Left" Margin="250,15,0,0" VerticalAlignment="Top" Width="120" Name="CBxerisim" SelectionChanged="CBxerisim_SelectionChanged" ItemsSource="{Binding Derisimkodu}" />
<ComboBox HorizontalAlignment="Left" Margin="250,45,0,0" VerticalAlignment="Top" Width="120" Name="CBxteklifDurum" SelectionChanged="CBxteklifDurum_SelectionChanged" ItemsSource="{Binding Dteklifdurumu}"/>
<ComboBox HorizontalAlignment="Left" Margin="250,75,0,0" VerticalAlignment="Top" Width="120" Name="CBxteklifSonuc" SelectionChanged="CBxteklifSonuc_SelectionChanged" ItemsSource="{Binding Dteklifsonuc}"/>
最佳答案
您需要设置以下属性(我假设您的 ObservableDictionary
继承自 IDictionary<TKey, TValue>
):
SelectedValuePath="Key" DisplayMemberPath="Value"
我已经使用 this 进行了测试实现ObservableDictionary<TKey, TValue>
在我看来:
<ComboBox Width="35" SelectedValuePath="Key" DisplayMemberPath="Value" ItemsSource ="{Binding FirstDictionary}"/>
还有我的 View 模型:
public class ViewModel
{
private ObservableDictionary<int, string> _firstDictionary;
public ViewModel()
{
_firstDictionary = new ObservableDictionary<int, string>()
{
new KeyValuePair<int, string>(1, "A"),
new KeyValuePair<int, string>(2, "B"),
new KeyValuePair<int, string>(3, "C")
};
}
public ObservableDictionary<int, string> FirstDictionary
{
get { return _firstDictionary; }
set { _firstDictionary = value; }
}
}
关于c# - ObservableDictionary 绑定(bind)到组合框显示值(MVVM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29176922/