【发布时间】:2010-10-14 22:45:15
【问题描述】:
walkthrough 说您可以在一行中创建 WPF 数据网格,但没有给出完整的示例。
所以我使用通用列表创建了一个示例并将其连接到 WPF 数据网格,但它没有显示任何数据。
我需要对下面的代码进行哪些更改才能使其在数据网格中显示数据?
答案:
此代码现在可以使用:
XAML:
<Window x:Class="TestDatagrid345.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
xmlns:local="clr-namespace:TestDatagrid345"
Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">
<StackPanel>
<toolkit:DataGrid ItemsSource="{Binding}"/>
</StackPanel>
</Window>
代码隐藏:
using System.Collections.Generic;
using System.Windows;
namespace TestDatagrid345
{
public partial class Window1 : Window
{
private List<Customer> _customers = new List<Customer>();
public List<Customer> Customers { get { return _customers; }}
public Window1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DataContext = Customers;
Customers.Add(new Customer { FirstName = "Tom", LastName = "Jones" });
Customers.Add(new Customer { FirstName = "Joe", LastName = "Thompson" });
Customers.Add(new Customer { FirstName = "Jill", LastName = "Smith" });
}
}
}
【问题讨论】:
-
只需将 DataContext = Customers 移动到您实际调用 Customers.Add 的位置下方!您正在使用 List
现在有更改通知!如果您确实需要更改通知,请使用 ObservableCollection