C# ObservableDictionary绑定到组合框显示值(MVVM)
我在数据绑定方面有问题。我有一个WPF(MVVM)用户控制项目。有C# ObservableDictionary绑定到组合框显示值(MVVM),c#,wpf,xaml,mvvm,combobox,C#,Wpf,Xaml,Mvvm,Combobox,我在数据绑定方面有问题。我有一个WPF(MVVM)用户控制项目。有组合框和标签。每个组合框都绑定到一个observedictionary。所以我的问题是,我只需要在我的组合框上显示字典的字符串部分 此外,Combobox ItemSource的更改取决于在前面的Combobox中选择的内容。这也是MVVM模式。有一个模型和视图模型 我尝试设置DisplayPath等,但无法在组合框上仅显示字符串。总是看到[0,示例],[1,是] <ComboBox HorizontalAlignment=
组合框
和标签
。每个组合框
都绑定到一个observedictionary
。所以我的问题是,我只需要在我的组合框上显示字典的字符串部分
此外,Combobox ItemSource
的更改取决于在前面的Combobox
中选择的内容。这也是MVVM模式。有一个模型和视图模型
我尝试设置DisplayPath
等,但无法在组合框上仅显示字符串。总是看到[0,示例]
,[1,是]
<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}"/>
您需要设置以下属性(我假设您的
observedictionary
继承自IDictionary
):
我已经使用observedictionary
我认为:
<ComboBox Width="35" SelectedValuePath="Key" DisplayMemberPath="Value" ItemsSource ="{Binding FirstDictionary}"/>
和我的视图模型:
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; }
}
}
公共类视图模型
{
私人医疗词典;
公共视图模型()
{
_firstDictionary=new ObservableDictionary()
{
新的KeyValuePair(1,“A”),
新的KeyValuePair(2,“B”),
新的KeyValuePair(3,“C”)
};
}
公共医学词典
{
获取{return\u firstDictionary;}
设置{u firstDictionary=value;}
}
}
试试这个:
<ComboBox DisplayMemberPath="Value"></ComboBox>
您可以将SelectedValuePath属性与属性名用作简单字符串的方式相同(它不是常规绑定) 假设您的类型“observedictionary”是一个普通的或来自字典的索引,您可以从组合框绑定显示和值
comboBox.ItemsSource = dictionary; // your collection
comboBox.SelectedValuePath = "Key"; // dictionary key
comboBox.DisplayMemberPath = "Value"; // dictionary content
如果用户没有添加或删除项目,我建议使用一个简单的列表
comboBox.ItemsSource = dictionary; // your collection
comboBox.SelectedValuePath = "Key"; // dictionary key
comboBox.DisplayMemberPath = "Value"; // dictionary content