【问题标题】:Confusion on Binding UWP DataGrid to MVVM model将 UWP DataGrid 绑定到 MVVM 模型的困惑
【发布时间】:2019-09-28 17:10:48
【问题描述】:

在这个MSDN tutorial 中,他们使用Model-View-ViewModel [MVVM] 将DataGrid 绑定到使用{x:Bind} markup extension 的客户列表,如下所示:

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

他们有一个Customer 类如下:

//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 在哪里?

备注:我使用的是VS2019的最新6.3.1版

【问题讨论】:

    标签: c# uwp xbind


    【解决方案1】:

    教程似乎不完整。

    但是,MyViewModel 可以是一个具有public ObservableCollection&lt;Customer&gt; Customers {get; set; } 属性的公共类。

    示例: MainPage.xaml.cs

    public class MainPage : ...
    {
       public MyViewModel MyViewModel { get; set; } = new MyViewModel();
    
       public MainPage()
       {        
       }
    }
    
    public class MyViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<Customer> Customers { get; set;} = new ObservableCollection<Customer>();
    }
    

    【讨论】:

    • {x:Bind} markup extension 似乎没有使用DataContextINotifyPropertyChanged。请参阅this 文章的x:Bind &amp; Binding Default behaviorx:Bind and INotifyPropertyChanged 部分。
    • @nam: 确实因为 {x:Bind} 需要强类型源(即在编译时已知)它不使用DataContext,而是使用顶部-级别容器元素作为源。但是,除此之外,它还具有 {Binding} 所具备的所有最常用功能,包括响应INotifyPropertyChanged,前提是您从一次性的默认模式更改为其他模式。您链接到的 codeproject.com 文章具有令人震惊的误导性。
    【解决方案2】:

    该教程中的 MyViewModel 在哪里?

    MyViewModel 应该是 MainPage.xaml.cs 的一个属性,它返回一个类的实例,该类的一个 Customers 属性返回一个 IEnumerable&lt;Customer&gt;

    {x:Bind} 标记扩展似乎没有使用 DataContext 或 INotifyPropertyChanged

    确实,它不使用DataContext,而是生成从源属性获取值的代码,并将其设置在标记中指定的目标属性上。这比在运行时使用反射解析绑定路径要快。

    INotifyPropertyChanged 和属性更改通知仍然适用于{x:Bind}

    【讨论】:

      猜你喜欢
      • 2016-08-28
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多