首页 > 解决方案 > 将 WPF DataGrid 升级到 UWP 支持的 DataGrid

问题描述

我正在将 WPF 应用程序升级到 UWP,并且一直在升级 DataGrid 控件。我正在尝试升级 System.Windows.Controls.DataGrid(旧的 WPF 控件)-> Microsoft.Toolkit.Uwp.UI.Controls.DataGrid(新的 MS 推荐的社区控件)

旧版本运行良好。它从 .NET DataTable 填充网格。XAML:

<DataGrid SelectionMode="Single" SelectionChanged="dataGridSongs_SelectionChanged" BorderThickness="1" BorderBrush="LightGray" Margin="0 0" IsReadOnly="True" GridLinesVisibility="None" Name="dataGridSongs" ItemsSource="{Binding}">
</DataGrid>

后面的代码:

public MainWindow()
{
    initializing = true;
    InitializeComponent();
    DataTable dt = dbHelper.GetAllSongs();
    dataGridSongs.DataContext = dt.DefaultView;
    dataGridSongs.HeadersVisibility = DataGridHeadersVisibility.None;
    initializing = false;
}

新的 UWP DataGrid 给了我一个错误:“BindingExpression 路径错误:在 'System.Data.DataRowView' 上找不到 'Item' 属性”并且网格中填充了一些奇怪的数据: 错误数据

新的 UWP 应用 XAML:

<controls:DataGrid x:Name="dataGridSongs" ItemsSource="{Binding}">
</controls:DataGrid>

后面的代码:

public MainPage()
{
    initializing = true;
    this.InitializeComponent();
    DataTable dt = dbHelper.GetAllSongs();
    dataGridSongs.DataContext = dt.DefaultView;
    //dataGridSongs.ItemsSource = dt.DefaultView;
}

我假设我用错误的对象填充网格,但是,我找不到这个简单场景的任何示例。

标签: c#wpfxamluwpdatagrid

解决方案


您可以参考以下示例,该示例显示如何将 a 绑定DataGrid到数据源:

public class Customer
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public String Address { get; set; }
    public Boolean IsNew { get; set; }

    public Customer(String firstName, String lastName,
        String address, Boolean isNew)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Address = address;
        this.IsNew = isNew;
    }
}
public class ViewModel
{
    private List<Customer> m_customers;
    public List<Customer> Customers { get { return m_customers; }
    }
    public ViewModel()
    {
        m_customers = new List<Customer>(new Customer[4] {
        new Customer("A.", "Zero",
            "12 North Third Street, Apartment 45",
            false),
        new Customer("B.", "One",
            "34 West Fifth Street, Apartment 67",
            false),
        new Customer("C.", "Two",
            "56 East Seventh Street, Apartment 89",
            true),
        new Customer("D.", "Three",
            "78 South Ninth Street, Apartment 10",
            true)
    });
    }
}

主页类

public sealed partial class MainPage : Page
{
    public ViewModel MyViewModel;
    public MainPage()
    {
        this.InitializeComponent();
        MyViewModel = new ViewModel();
    }
}

主页.xaml

    <controls:DataGrid x:Name="dataGrid"  AutoGenerateColumns="True"
                       ItemsSource="{x:Bind MyViewModel.Customers}">
    </controls:DataGrid>

您可以参考文档以获取有关数据绑定和自定义列的更多信息DataGrid


推荐阅读