使用MVVM进行UWP DataGrid数据绑定的问题 [英] Question on UWP DataGrid data binding using MVVM

查看:29
本文介绍了使用MVVM进行UWP DataGrid数据绑定的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For the first time trying to use MVVM to bind data in a .NET app. Coming from a legacy .NET world, I'm not quite understanding the use of MVVM in a UWP app.

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

I'm trying to bind following DataGrid control in my UWP app with my MVVM (shown below) that is a class created on the top level of the project named My_UWP_Project. Question: To populate customer data, what value should I add to ???? of ItemsSource="{x:Bind ????}" line of DataGrid control?

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

Remark: For data binding, I'm using new approach recommended by Microsoft {x:Bind} markup extension as apposed to Binding class.

MainPage.xaml 中的 DataGrid 控件:

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

客户类 [ViewModel]:

Customer class [ViewModel]:

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 方法.

It's been a while I don't develop UWP apps but as I remember you can directly bind viewmodel's property or method with x:Bind approach.

首先定义你的视图模型

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

然后在绑定时使用它.

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

这篇关于使用MVVM进行UWP DataGrid数据绑定的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆