首页 > 解决方案 > 关于 UWP 上 DataGrid 的文档不清楚

问题描述

因此,随着我的进展,我正在关注有关DataGrid使用 windows 工具包的文档。有一个示例代码

这个

<controls:DataGrid x:Name="dataGrid1" 
    Height="600" Margin="12"
    AutoGenerateColumns="True"
    ItemsSource="{x:Bind MyViewModel.Customers}" />  

这是我这边的代码

<controls:DataGrid x:Name="dgvTest"
                           Height="800"
                           Margin="1"
                           AutoGenerateColumns="True"
                           ItemsSource="{x:Bind }">

在我尝试的时候。我似乎找不到 MyViewModel 来自哪里。

更进一步,他们有这个代码

//backing data source in MyViewModel
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 static List<Customer> Customers()
    {
        return 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)
        });
    }
}

所以肯定 MyViewModel 不是类,因为Customer是类,而 GitHub 页面上的示例行有这一行

private DataGridDataSource viewModel = new DataGridDataSource();

但是每当我尝试将其添加到我的代码中时,我都会遇到一个错误,即

错误 CS0246 找不到类型或命名空间名称“DataGridDataSource”(您是否缺少 using 指令或程序集引用?)

很抱歉,如果我听起来像个业余爱好者,但是当我DataGridView使用 WinForms 时,我从未遇到过这个问题。

任何帮助,将不胜感激。谢谢

标签: c#xamluwpdatagrid

解决方案


该类DataGridDataSource可在此处找到:https ://github.com/windows-toolkit/WindowsCommunityToolkit/blob/35ffc09c4cba6354eb7d9dcac1f97c554ac5df68/Microsoft.Toolkit.Uwp.SampleApp/Data/DataGridDataSource.cs

如果你x:BindMyViewModel.Customers你的 XAML 中,MyViewModel应该是页面类的一个属性,它返回一个类的实例,该类的Customers属性返回一个List<Customer>

public class DataGridDataSource
{
    public List<Customer> Customers => Customer.Customers();
}

public sealed partial class MainPage : Page
{
    public DataGridDataSource MyViewModel => new DataGridDataSource();

    public MainPage()
    {
        InitializeComponent();
    }
}

如果您查看docs 中的最后一个示例,您会看到MainPage.xaml.cs该类具有一个List<Person>名为“Persons”的属性,该属性DataGrid绑定到:

ItemsSource="{x:Bind Persons}"

推荐阅读