如何将 WPF ComboBox 绑定到 XAML 中的 List<Objects>?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42422427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 14:01:08  来源:igfitidea点击:

How do I bind a WPF ComboBox to a List<Objects> in XAML?

c#wpfxamlcombobox

提问by JohnB

I'm having issues binding a WPF ComboBox in XAML.

我在 XAML 中绑定 WPF ComboBox 时遇到问题。

Here is my object definition and collection:

这是我的对象定义和集合:

public class AccountManager
{
   public long UserCode { get; set; }
   public string UserName { get; set; }
}

public partial class MainWindow : Window
{    
   public List<AccountManager> AccountManagers;
}

Here is the XAML definition of my ComboBox:

这是我的 ComboBox 的 XAML 定义:

ComboBox Name="cbTestAccountManagers"
          ItemsSource="{Binding AccountManagers}"
          DisplayMemberPath="UserName"
          SelectedValuePath="UserCode"
          Width="250"

I'm not quite sure what I'm doing wrong here. I don't get any errors at run/load time. The ComboBox displays without any contents in the drop down. (It's empty).

我不太确定我在这里做错了什么。我在运行/加载时没有收到任何错误。ComboBox 在下拉列表中不显示任何内容。(它是空的)。

Can someone point me in the right direction?

有人可以指出我正确的方向吗?

Thanks

谢谢

采纳答案by Noah Reinagel

Your problem is simple. Change

你的问题很简单。改变

public List<AccountManager> AccountManagers; 

to this

对此

public List<AccountManager> AccountManagers { get; set; }

and make sure that you have these in your MainWindow constructor

并确保您的 MainWindow 构造函数中有这些

public MainWindow()
{
    InitializeComponent();
    //Setup Account managers here
    DataContext = this;
}

you can only bind to properties not fields and you need to ensure the proper data context

您只能绑定到属性而不是字段,并且您需要确保正确的数据上下文

回答by MikeT

your making a couple of mistakes

你犯了几个错误

firstly you're not following MVVM

首先你没有关注 MVVM

the correct MVVM should look as follows

正确的 MVVM 应如下所示

public class AccountManager
{
   public long UserCode { get; set; }
   public string UserName { get; set; }
}
public class AccountManagersVM
{
   public ObservableCollection<AccountManager> AccountManagers{ get; set; }

}

then no need for changes to the code behind you just need to use the DataContext which can be set directly or via a binding

那么不需要更改背后的代码只需要使用可以直接或通过绑定设置的 DataContext

<Window.DataContext>
    <local:AccountManagersVM />
</Window.DataContext>
ComboBox ItemsSource="{Binding AccountManagers}"
          DisplayMemberPath="UserName"
          SelectedValuePath="UserCode"
          Width="250"

Second attributes/fields can't be bound only properties

第二个属性/字段不能只绑定属性

eg public long UserCode { get; set; }will work but public long UserCode;wont

例如public long UserCode { get; set; }会工作但public long UserCode;不会