【问题标题】:Trouble binding ComboBox to ObservableCollection<>无法将 ComboBox 绑定到 ObservableCollection<>
【发布时间】:2016-05-05 09:57:01
【问题描述】:

我在将 ObserveableCollection 绑定到组合框时遇到了一些问题。 为了给出一些观点,我有一个这样的课程:

class LogOnUser
{
    #region Members
    string _UserName;
    string _Password;
    #endregion

    #region Construction
    public LogOnUser(string username)
    {
        _UserName = username;
    }

    public LogOnUser(string username, string password)
    {
        _UserName = username;
        _Password = password;
    }
    #endregion

    #region Properties
    public string Username
    {
        get { return _UserName; }
        set { _UserName = value; }
    }

    public string Password
    {
        get { return _Password; }
        set { _Password = value; }
    }
    #endregion
}

然后我有另一个在 ObserveableCollection 中使用 LogOnUser 的类:

class LogOnUserCollection: ObservableCollection<LogOnUser>
{
    public LogOnUserCollection() : base()
    {
        Add(new LogOnUser("User1", "password"));
        Add(new LogOnUser("User2", "password"));
    }
}

我在一个名为LogOnUsers 的ViewModel 中有一个LogOnUserCollection 实例,我将它绑定到我的视图中组合框的ItemsSource。但是我只想显示我的集合的Username 属性,因此它将具有“User1”和“User2”作为它的项目,但实际发生的是我的 ComboBox 只是显示“LogOnUsers.LogOnUser”作为它的两个项目. 有人可以告诉我我做错了什么吗?

更新绑定xaml代码

<UserControl x:Class="MVVM.View"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:MVVM"
         mc:Ignorable="d">

    <UserControl.DataContext>
        <local:PasswordEntryViewModel/>
    </UserControl.DataContext>

    <UserControl.Resources>
        <local:LogOnUserCollection x:Key="LogOnUserCollection"/>
    </UserControl.Resources>

    <Grid>
        <ComboBox ItemsSource="{Binding LogOnUserCollection}"/>
    </Grid>
</UserControl>

【问题讨论】:

  • 您是否在 ComboBox 上设置了 DisplayMember?
  • 能否请您提供绑定代码
  • 是的,没有 xaml 就没有猜测
  • 抱歉,我现在已经添加了 xaml。

标签: c# wpf binding combobox


【解决方案1】:

您需要设置更多属性,而不仅仅是 ItemsSource

典型的组合框通常看起来像 --

<ComboBox ItemsSource="{Binding ITEMS}"
              DisplayMemberPath="PROPERTY_NAME"
              SelectedItem="{Binding SELECTED_ITEM}"/>

显示成员会告诉应该使用哪个属性在组合框中显示文本。

顾名思义,所选项目将为您提供所选项目,以便您可以使用它。 (虽然所选项目与您的问题没有直接关系,但在大多数情况下您会使用它)

【讨论】:

  • 谢谢,成功了!我是否认为 SELECTED_ITEM 只是我的 ViewModel 中的一个字符串?
  • 所选项目是绑定到组合框的对象类型,因此在您的情况下,它的类型为 LogOnUser
【解决方案2】:

尝试如下图设置显示成员路径;

<ComboBox ItemsSource="{Binding LogOnUserCollection}"
      DisplayMemberPath="Username"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-03
    • 2013-04-18
    • 2014-05-25
    • 2016-09-25
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    相关资源
    最近更新 更多