简体   繁体   中英

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

     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.

You have 2 options. First you can change your xaml to this notice how we bind to the property in the item template.

<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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