我知道这是一个常见的问题,但就我从其他帖子中看到的情况而言,我做的一切都很正确......显然我不是。
我背后的代码中的C#
InitializeComponent();
cboCustomerIds.DataContext = new Customers();
业务对象层中的我的C#
namespace BusinessObjects
{
public class Customers
{
public class Customer
{
public Int64 CustomerId { get; set; }
}
public List<int> CustomerIds { get; set; }
public Customers()
{
DataLayer dl = new DataLayer();
SqlDataReader reader = dl.GetSqlDataReader("GetCustomerIds");
List<Int64> CustomerIds = new List<Int64>();
try
{
if (reader.HasRows)
{
do
{
Int64 thing = 0;
thing = (Int64)reader["CustomerId"];
CustomerIds.Add(thing);
int count = CustomerIds.Count;
Int64 id = CustomerIds[count-1];
}
while (reader.Read());
}
}
catch
{
throw;
}
finally
{
reader.Close();
}
}
}
}
C#计算CustomerIds,因此我可以调用并确认从数据库返回的项目并添加到列表中。 我的XAML
<Grid>
<ComboBox x:Name="cboCustomerIds" ItemsSource="{Binding CustomerIds}" DisplayMemberPath="CustomerId" Width="120">
</ComboBox>
</Grid>
它构建没有错误并运行。它调用Customers构造函数并构建CustomerIds列表,但cboCustomerIds显示一个空列表。
答案 0 :(得分:1)
仔细检查您的代码,永远不会引用这些代码。
public class Customer
{
public Int64 CustomerId { get; set; }
}
public List<int> CustomerIds { get; set; }
您从数据库中读取数据并将其添加到
中 List<Int64> CustomerIds = new List<Int64>();
不进入
public List<int> CustomerIds { get; set; }
但ComboBox与public List<int> CustomerIds { get; set; }
绑定
所以一切看起来都很奇怪。
以下是一个例子:
public class Customers
{
public List<int> CustomerIds { get; set; }
public Customers()
{
CustomerIds = new List<int>();
for (int i = 1; i < 10; i++)
{
CustomerIds.Add(i);
}
}
}
并且您应该首先删除DisplayMemberPath。
我猜您的要求是:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
cboCustomerIds.DataContext = new Customers();
}
}
/// <summary>
/// ViewModel
/// </summary>
public class Customers
{
public List<Customer> LstCustomer { get; set; }
public Customers()
{
LstCustomer = new List<Customer>();
//get data from DB, here is an example
for (int i = 1; i < 10; i++)
{
Customer c = new Customer();
c.CustomerId = i;
c.CustomerName = "name" + i;
c.CustomerAge = 10 + i;
LstCustomer.Add(c);
}
}
}
/// <summary>
/// Model
/// </summary>
public class Customer
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public int CustomerAge { get; set; }
}
和View
:
<ComboBox x:Name="cboCustomerIds" ItemsSource="{Binding LstCustomer}" DisplayMemberPath="CustomerId" />