c# - 将 TextBox 绑定(bind)到字典的键

标签 c# wpf dictionary

我目前正在使用 MVVM Light Toolkit 并在 WPF C# 中创建应用程序。我目前在我的 XAML 中有一个 ComboBox,如下所示:

<ComboBox Height="23" HorizontalAlignment="Left" Margin="367,39,0,0" Name="comboBox1" VerticalAlignment="Top" Width="156" ItemsSource="{Binding Combo_Major_Commands}"/>

在代码中:

private Dictionary<string, string> _combo_Major_Commands;
public Dictionary<string, string> Combo_Major_Commands
{
    get { return _combo_Major_Commands; }
    private set;
}

现在在我的运行时代码中我初始化它并添加我需要的项目,如下所示:

_combo_Major_Commands = new Dictionary<string, string>();
_combo_Major_Commands.Add("Standby", "STBY");
_combo_Major_Commands.Add("Operate", "OPER");
_combo_Major_Commands.Add("Remote", "REMOTE");
_combo_Major_Commands.Add("Local", "LOCAL");

有什么方法可以将我的 ComboBox 绑定(bind)到键值吗?目前它绑定(bind)到整个值并显示以下内容

[Standby, STBY]

在组合框中。

最佳答案

您需要通过在 ComboBox 上设置 DisplayMemberPath 来设置要显示 KeyValuePair 的哪一部分:

<ComboBox ... ItemsSource="{Binding Combo_Major_Commands}" DisplayMemberPath="Key"/>

关于c# - 将 TextBox 绑定(bind)到字典的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17655278/

相关文章:

c# - 无法将图像添加到 C# WPF .Net Core WPF 应用程序

C# wpf 如何从 Main 调用 initializeComponent

绑定(bind)到在单独线程上更新的 ObservableCollection 的 WPF DataGrid 无法维护排序

c# - 如何在不更改主机文件的情况下阻止对特定站点的访问,直到重新启动?

arrays - 在 Swift 中访问属于数组的字典中的值

c++ - 尝试初始化将对象作为构造函数中的值的映射

python - 如何通过组合两个列表中的项目来创建字典?

c# - RoutedUICommand PreviewExecuted Bug?

c# - 如何从 C# 中的智能卡读取凭据

c# - 如何使用正确的参数类型从 C# 正确调用 C++ DLL