XAML WinUI 3:如何绑定到DataTemplate中的数据本身?

bt1cpqcv  于 2023-02-27  发布在  其他
关注(0)|答案(1)|浏览(247)

考虑列表视图:

<ListView ItemsSource="{x:Bind People}">
  <ListView.ItemTemplate x:DataType="models:Person">
    <controls:PersonItem Person="{...}" />
  </ListView.ItemTemplate>
</ListView>

在本例中,People是在代码隐藏中定义的ObservebleCollection<Person>类型的属性。类Person定义如下:

public class Person : INotifyPropertyChanged
{
  public virtual Guid Id { get; set; }
  public virtual string Name { get; set; }

  // The implemention of INotifyPropertyChanged:
  ...
}

控件PersonItem是定义了DependencyProperty的自定义用户控件,称为Person,并接收Person对象作为值。此控件将使用此属性的成员在屏幕上显示一些信息。

我想知道的是如何将Person属性绑定到数据模板中的数据本身,换句话说,应该使用什么来替换第一个代码片段中的...

虽然我知道Person中的属性太少了,我可以简单地在我的自定义控件中将每个属性定义为DependencyProperty,但我遇到的实际情况是,我得到了一个类,它有太多的属性需要在一个控件中使用,那么我需要做的工作就太多了。

ecr0jaav

ecr0jaav1#

x:BindBinding应该都可以工作。

using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;

namespace WinUI3App;

public sealed class PersonItem : Control
{
    public static readonly DependencyProperty PersonProperty =
        DependencyProperty.Register(
            nameof(Person),
            typeof(Person),
            typeof(PersonItem),
            new PropertyMetadata(null, OnPersonPropertyChanged));

    public PersonItem()
    {
        this.DefaultStyleKey = typeof(PersonItem);
    }

    public Person Person
    {
        get => (Person)GetValue(PersonProperty);
        set => SetValue(PersonProperty, value);
    }

    private static void OnPersonPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (e.NewValue is Person person)
        {
        }
    }
}
using Microsoft.UI.Xaml;
using System;
using System.Collections.ObjectModel;

namespace WinUI3App;

public class Person
{
    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; } = string.Empty;
}

public sealed partial class MainWindow : Window
{
    public MainWindow()
    {
        this.InitializeComponent();

        for (int i = 0; i < 10; i++)
        {
            People.Add(new Person()
            {
                Id = Guid.NewGuid(),
                Name = Guid.NewGuid().ToString(),
            });
        }
    }

    public ObservableCollection<Person> People { get; set; } = new();
}
<Window
    x:Class="WinUI3App.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="using:WinUI3App"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <ListView ItemsSource="{x:Bind People}">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="local:Person">
                <!--<local:PersonItem Person="{Binding}" />-->
                <local:PersonItem Person="{x:Bind}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

</Window>

相关问题