如何在WPF中将简单列表绑定到DataGrid [英] How to Bind a simple List to DataGrid in WPF
问题描述
我有一个
具有某些属性的Data Holder类
I have a
Data Holder class with some properties
public string Name
{
get;
set;
}
public string No
{
get;
set;
}
public IList<Customer> CustomerData
{
get;
set;
}
public Customer()
{
IList<Customer> customerList = new List<Customer>();
this.Name = "Adam";
this.No = "1";
customerList.Add(this);
CustomerData = customerList;
}
并在我的Xaml中尝试将其绑定到我的网格
and in my Xaml I am trying to bind it to my grid
<DataGrid Name="Sampledatagrid" AutoGenerateColumns="True" ItemsSource="{Binding CustomerData}" Margin="0,0,0,106" />
我没有得到更新的CustumerData
我在想什么吗?
请告知
I am not getting the updated CustumerData
Am i missing somthing ??
please advise
推荐答案
我认为您需要像这样以自己的方式将客户列表创建为类
I think you need to create the List of customers as a class in it''s own right like this
public class Customer
{
public string Name
{
get;
set;
}
public int No
{
get;
set;
}
public Customer()
{
}
}
public class Customers : List<Customer>
{
public Customers()
{
this.Add(new Customer() { Name = "Adam", No = 1 });
}
}
那么您可以在窗口中创建静态或动态资源,并像这样绑定到资源
then you can create a Static or Dynamic Resource in your Window and bind to the Resource like this
<Window.Resources>
<local:Customers x:Key="MyCustomers"/>
</Window.Resources>
并像这样创建您的DataGrid
and create your DataGrid like this
<DataGrid Name="Sampledatagrid" AutoGenerateColumns="True" ItemsSource="{StaticResource MyCustomers}" Margin="0,0,0,106"/>
这样,即使在设计器中,您也应该能够立即查看数据.
假设您已经声明了Customer类所在的名称空间,并且已将其命名为local
and then you should be able to see your data straight away even in the designer.
This assumes that you have declared your namespace that the Customer class is in and you have called it local like this
xmlns:local="clr-namespace:yourApplication"
希望这对您有帮助
Hope this helps
据我所见,您尚未将Customer类分配给DataContext
.否则,您的Binding
将无法正常工作.
From what I can see here, you haven''t assigned the Customer class to theDataContext
. Without doing that, yourBinding
will not work.
这篇关于如何在WPF中将简单列表绑定到DataGrid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!