c# - 如何将 WPF ComboBox 绑定(bind)到 XAML 中的 List<Objects>?

标签 c# wpf xaml combobox

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

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

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

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

这是我的 ComboBox 的 XAML 定义:

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

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

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

谢谢

最佳答案

你的问题很简单。 改变

public List<AccountManager> AccountManagers; 

对此

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

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

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

你只能绑定(bind)到属性而不是字段,你需要确保正确的数据上下文

关于c# - 如何将 WPF ComboBox 绑定(bind)到 XAML 中的 List<Objects>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42422427/

相关文章:

c# - 在 View 模型和 View 之间使用 MVVM 的 Wpf 数据上下文绑定(bind)

.net - 当属性 Visibility 更改时为 StackPanel 设置动画

wpf - 使用 CanUserResize ="True"调整数据网格列的大小在 WPF 中不起作用

c# - 网格中无行和无列子项的奇怪行为

c# - 为什么我的隐式 ContextMenu 样式不会覆盖 TextBox 上下文菜单样式?

c# - 如何从文本框中删除CSS?

c# - 将消息从 Azure 服务总线队列发送到新的 asb 队列

c# - 如何在 C# 中将 DataRowView 转换为 DataRow

c# - Format string in ICS Fle(为 ICS 文件设置字体)

c# - 仅从字符串中取出数字并放入数组中