简体   繁体   English

将表值绑定到Combobox时出错 - wpf

[英]Error on binding table value to Combobox - wpf

I have a combobox which should bind the data dynamically from the database . 我有一个组合框,它应该从数据库动态绑定数据。

The source of the combobox is a observable collection. 组合框的来源是可观察的集合。

Steps I followed: 我遵循的步骤:

  1. Declared a combobox : 宣布一个组合框:

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

     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. Instantiating the above mentioned class in viewmodel 在viewmodel中实例化上述类

     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(); } 

    } }

The expected output is : 预期的产出是:

Ren1
Ren2

The actual output is 实际输出是

Namespace.Model.comboxdata
Namespace.Model.comboxdata

You are getting the output of the ToString() method and you are binding to instances of comboboxdata class and not the username inside of it. 您正在获取ToString()方法的输出,并且您绑定到comboboxdata类的实例而不是其中的用户名。

You have 2 options. 你有2个选择。 First you can change your xaml to this notice how we bind to the property in the item template. 首先,您可以将xaml更改为此通知我们如何绑定到项目模板中的属性。

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

Second you can override the ToString() method on comboboxdata to return the username 其次,您可以覆盖comboboxdata上的ToString()方法以返回用户名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM