繁体   English   中英

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

[英]Error on binding table value to Combobox - 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. 在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(); } 

    }

预期的产出是:

Ren1
Ren2

实际输出是

Namespace.Model.comboxdata
Namespace.Model.comboxdata

您正在获取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>

其次,您可以覆盖comboboxdata上的ToString()方法以返回用户名

暂无
暂无

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

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