Question on UWP DataGrid data binding using MVVM

老子叫甜甜 提交于 2019-12-11 15:29:55

问题


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.

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?

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

DataGrid control in MainPage.xaml:

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

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)
        });
        }
    }
}

回答1:


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.

First define the your viewmodel

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

and then use it on binding.

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


来源:https://stackoverflow.com/questions/58141641/question-on-uwp-datagrid-data-binding-using-mvvm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!