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

问题描述 投票:0回答:1
c# wpf xaml uwp winui-3
1个回答
0
投票

x:Bind
Binding
应该工作。

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>
© www.soinside.com 2019 - 2024. All rights reserved.