关于UWP上的DataGrid的文档尚不清楚

时间:2019-01-09 13:05:34

标签: c# xaml uwp datagrid

因此,随着我逐步深入,我正在使用Windows工具包关注有关DataGrid的文档。有示例代码

这个

<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页面上的sammple行具有该行

private DataGridDataSource viewModel = new DataGridDataSource();

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

  

错误CS0246类型或名称空间名称'DataGridDataSource'无法   被发现(您是否缺少using指令或程序集   参考?)

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

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

1 个答案:

答案 0 :(得分:1)

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

如果您在XAML中从x:BindMyViewModel.Customers,则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();
    }
}

如果您查看last example in the docs,则会发现MainPage.xaml.cs类具有一个List<Person>绑定到的DataGrid属性,称为“ Persons”:

ItemsSource="{x:Bind Persons}"