c# - 将简单的 List<myClass> 绑定(bind)到 Combobox

标签 c# .net wpf combobox

我想将我的类(class)列表绑定(bind)到 WPF 中的 CombpBox。我觉得应该很简单。

我尝试了代码,但它不起作用:

    public MainWindow()
    {

        InitializeComponent();

        List<SimpleClass> ListData = new List<SimpleClass>();
        ListData.Add(new SimpleClass { Id = "1", Value = "One" });
        ListData.Add(new SimpleClass { Id = "2", Value = "Two" });
        ListData.Add(new SimpleClass { Id = "3", Value = "Three" });
        ListData.Add(new SimpleClass { Id = "4", Value = "Four" });
        ListData.Add(new SimpleClass { Id = "5", Value = "Five" });


        comboBox1.DataContext = ListData;
        comboBox1.DisplayMemberPath = "{Binding Path=Value}";
        comboBox1.SelectedValuePath = "{Binding Path=Id}";


    }
}
public class SimpleClass
{
    public string Id;
    public string Value;
}

XAML如下

 <ComboBox Height="23" HorizontalAlignment="Left" Margin="221,107,0,0" Name="comboBox1" ItemsSource="{Binding}" VerticalAlignment="Top" Width="120" />

我做错了什么?

最佳答案

应该是

comboBox1.DisplayMemberPath = "Value";
    comboBox1.SelectedValuePath = "Id";

在后面的代码中,您不能通过设置字符串来分配绑定(bind),这有点复杂。在这种情况下,DisplayMemberPathSelectedValuePath 只需要属性名称,而不需要绑定(bind)。

关于c# - 将简单的 List<myClass> 绑定(bind)到 Combobox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9174765/

相关文章:

c# - 在 C# 中使用 SqlCommand Prepare 的优点和缺点?

c# - 如何在运行时使用 MVVM 将 List<object> 绑定(bind)到 DataGrid

c# - 如何加载特定版本的程序集

c# - 如何创建非模态形式但阻塞?

c# - 有效地使用 XmlDocument.Save()

c# - WPF - 多行文本框文本在键入长文本时变得模糊

c# - 好奇 : Whats currently the recommended way of coding REST web services in C#?

c# - 以事务方式删除目录中的所有文件和文件夹

c# - UIElement.TranslatePoint 时不时返回 (0,0)

c# - 从 wpf 中检索 gridview 选定行中的值