【问题标题】:WPF Datagrid: No data being displaysWPF Datagrid:没有显示数据
【发布时间】:2010-11-19 09:05:43
【问题描述】:

谁能告诉我为什么我的 WPF DataGrid 中没有显示任何数据,代码如下:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300"
    xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit"
        >
    <Grid>
        <my:DataGrid Name="myDataGrid" ItemsSource="{Binding Customers}">
            <my:DataGrid.Columns>
                <my:DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                <my:DataGridTextColumn Header="Name1" Binding="{Binding Name1}" />
            </my:DataGrid.Columns>
        </my:DataGrid>
    </Grid>
</Window>

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();

        IList<Customers> list = new List<Customers>();
        list.Add(new Customers() { Name = "Name1", Name2 = "Name2" });
        list.Add(new Customers() { Name = "Name1", Name2 = "Name2" });
        list.Add(new Customers() { Name = "Name1", Name2 = "Name2" });

        myDataGrid.DataContext = new Customers() { Name = "Name1", Name2 = "Name2" };
    }
}

public class Customers
{
    public string Name { get; set; }
    public string Name2 { get; set; }
}

【问题讨论】:

    标签: c# wpf vb.net datagrid


    【解决方案1】:

    嗯。这里有很多问题。

    1. 您将DataContext 设置为new Customers() 对象而不是客户集合(即list
    2. 应该有 ItemsSource="{Binding}" 以便将 ItemsSource 直接绑定到将成为集合的 DataContext。
    3. 据我所知,DataGridAutoGenerateColumns 默认为 true,因此它将有 4 列,2 列由您自己创建,2 列自动生成。

    【讨论】:

    • Ups,在我的代码中,我确实将 DataContext 设置为我的列表。您在上面提出的第 2 点解决了问题,谢谢
    【解决方案2】:

    除了 alpha-mouse 所说的一切,这一切都是为了钱......

    考虑让你的数据上下文成为 ObservableCollection 类型的类成员:

    public partial class Window1 : Window
    {
      private ObservableCollection<Customers> customers;
    
      public Window1()
      {
          InitializeComponent();
    
          this.customers = new ObservableCollection<Customers>();
    

    使用 ObservableCollection 而不是 List 可确保网格自动获取对集合内容的更改,而无需执行任何类型的 NotifyPropertyChanged。

    【讨论】:

    • 当然,您应该真正将 View 的 DataContext 设置为 ViewModel 类,并使您的 Customers 集合成为 ViewModel 上的一个属性。
    猜你喜欢
    • 2018-10-18
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 2016-03-15
    • 2011-10-22
    相关资源
    最近更新 更多