首页 > 解决方案 > 将表值绑定到组合框时出错 - wpf

问题描述

我有一个组合框,它应该从数据库中动态绑定数据。

组合框的来源是一个可观察的集合。

我遵循的步骤:

  1. 声明了一个组合框:

    <ComboBox ItemsSource="{Binding populatecombobox.modeltogetusername }" Width="155" Margin="18,15,618,0"/>
    
  2. 创建了一个类来从数据库中获取数据:

    public class populatetab2combobox
    {
        public ObservableCollection<comboboxdata> modeltogetusername { get; set; }
    
        public void getdatausinglinq()
        {
            using (Operations_Productivity_ToolEntities context = new Operations_Productivity_ToolEntities())
            {
                var a1 = from t1 in context.Test_ImportedAuditdata
                         select t1;
    
                if (modeltogetusername == null)
                    modeltogetusername = new ObservableCollection<comboboxdata>();
    
                foreach (var a in a1.GroupBy(x => x.username).Select(x => x.FirstOrDefault()))
                {
                    modeltogetusername.Add(new comboboxdata
                    {
                     username = a.username
                    });
    
                }
            }
    
        }
    
    }
    
  3. 在视图模型中实例化上述类

    public class ViewModel: INotifyPropertyChanged {
    private populatetab2combobox _populatecombobox = new populatetab2combobox();
    
    public populatetab2combobox populatecombobox {
        get {
            return _populatecombobox;
        }
        set {
            if (value != _populatecombobox) {
                _populatecombobox = value;
                OnPropertyChanged("populatecombobox");
            }
        }
    }
    public ViewModel() {
        _populatecombobox.getdatausinglinq();
    }
    

    }

预期的输出是:

Ren1
Ren2

实际输出为

Namespace.Model.comboxdata
Namespace.Model.comboxdata

标签: c#wpf

解决方案


您正在获取 ToString() 方法的输出,并且您正在绑定到 comboboxdata 类的实例,而不是其中的用户名。

您有 2 个选项。首先,您可以将您的 xaml 更改为此通知我们如何绑定到项目模板中的属性。

<ComboBox ItemsSource="{Binding populatecombobox.modeltogetusername }" Width="155" Margin="18,15,618,0">
  <ComboBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding username}"/>
    </DataTemplate>
  </ComboBox.ItemTemplate>
</ComboBox>

其次,您可以覆盖组合框数据上的 ToString() 方法以返回用户名


推荐阅读