有关使用 MVVM 绑定 UWP 数据网格数据的问题



第一次尝试使用 MVVM 在 .NET 应用程序中绑定数据。 来自传统的 .NET 世界,我不太了解MVVMUWP应用程序中的使用。

我正在尝试将 UWP 应用中的以下DataGrid控件与我的MVVM(如下所示(绑定,该是在名为My_UWP_Project的项目顶层创建的类。:若要填充客户数据,我应该向 DataGrid 控件行????添加什么值ItemsSource="{x:Bind ????}"

备注:对于数据绑定,我正在使用Microsoft {x:Bind}标记扩展推荐的新方法,作为绑定类的追加。

MainPage.xaml 中的 DataGrid 控件

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

客户类[视图模型]:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace My_UWP_Project
{
//backing data source
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)
});
}
}
}

我已经有一段时间没有开发 UWP 应用程序了,但我记得你可以使用x:Bind方法直接绑定 viewmodel 的属性或方法。

首先定义视图模型

<Page.DataContext>
<Customer x:Name="ViewModel" />
</Page.DataContext>

然后在绑定中使用它。

ItemsSource="{x:Bind ViewModel.Customers}"

最新更新