【发布时间】:2019-04-30 15:44:07
【问题描述】:
我正在尝试将列表绑定到 ComboBox 并使用 displaymemberpath 来显示值。
这是我的 XAML:
<ComboBox x:Name="ComboBoxCommissieGroep"
ItemsSource="{Binding Commissies}"
DisplayMemberPath="CommissieGroep">
视图模型:
我的 ViewModel 检索“佣金”列表
private async Task LoadData()
{
commissies = new ObservableCollection<object>(await LoginBLL.GetCommissiesList());
}
型号:
public class InloggenBO : ObservableObject
{
private int lidNummer;
public int LidNummer
{
get => lidNummer;
set
{
lidNummer = value;
NotifyPropertyChanged();
}
}
private string commissieGroep;
public string CommissieGroep
{
get => commissieGroep;
set
{
commissieGroep = value;
NotifyPropertyChanged();
}
}
private string wachtwoord;
public string Wachtwoord
{
get => wachtwoord;
set
{
wachtwoord = value;
NotifyPropertyChanged();
}
}
}
我的代码数据库方法: 该方法创建已从数据库中检索到的数据集列表。这就是为什么它是 object 类型而不是 InloggenBO
protected Task<List<object>> ExecuteReader(string SqlString)
{
// Read to dataset
DataSet dataset = new DataSet();
using (var conn = new SqlConnection(ConnectionString))
using (var adapter = new SqlDataAdapter(new SqlCommand(SqlString, conn)
{
// Set commandtype
CommandType = CommandType.Text
}))
{
// Open connection
conn.Open();
// Fill dataset
adapter.Fill(dataset);
// Close connection
conn.Close();
}
return Task.FromResult(ToList(dataset));
}
创建列表对象的方法
private List<object> ToList(DataSet dataSet)
{
var list = new List<object>();
foreach (var dataRow in dataSet.Tables[0].Rows)
{
list.Add(dataRow);
}
return list;
}
我已将我的 DataContext 设置为视图模型,并且我知道绑定有效,因为在我的组合框中没有显示成员路径它说:“System.Data.Datarow”。那么我必须在 displaymemberpath 中放入什么才能显示它的值?
【问题讨论】:
-
为什么你的 ObservableCollection 类型对象应该是 InloggenBO 类型?
-
同样在您的 XAML 中,您绑定到 Commissies,但您的虚拟机有一个名为 commissies 的属性(我假设)
-
@auburg 我编辑了关于如何检索数据的问题,以便您知道为什么我有一个 Object 类型的 ObservableCollection
-
您的
ToList(dataset)似乎返回了List<DataRow>- 那么为什么DataRow对象应该知道您的InloggenBO类的任何信息? -
因为您绑定到一个普通对象,所以没有 CommissieGroep 属性。您应该绑定到具有该属性名称的对象列表才能使其工作。
标签: c# wpf mvvm data-binding binding