簡體   English   中英

關於使用 MVVM 進行 UWP DataGrid 數據綁定的問題

[英]Question on UWP DataGrid data binding using MVVM

第一次嘗試使用MVVM在 .NET 應用程序中綁定數據。 來自傳統的 .NET 世界,我不太了解MVVMUWP應用程序中的使用

我正在嘗試將我的 UWP 應用程序中的以下DataGrid控件與我的MVVM (如下所示)綁定,該 MVVM 是在名為 My_UWP_Project 的項目的頂層創建的My_UWP_Project 問題:要填充客戶數據,我應該添加什么值???? ItemsSource="{x:Bind????}"行 DataGrid 控件?

備注:對於數據綁定,我使用 Microsoft {x:Bind} 標記擴展推薦的新方法,與Binding class 相對

MainPage.xaml 中的 DataGrid 控件

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

客戶 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方法直接綁定 viewmodel 的屬性或方法。

首先定義您的視圖模型

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

然后在綁定時使用它。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM