UWP DependencyProperty 绑定和 DataTemplate 绑定

UWP DependencyProperty Binding and DataTemplate Binding

我有一个 PlaylistControl(它是一个 UserControl),其中有一个以这种方式声明的变量 ShowAlbumText

    public bool ShowAlbumText
    {
        get => (bool)GetValue(ShowAlbumTextProperty);
        set => SetValue(ShowAlbumTextProperty, value);
    }
    public static readonly DependencyProperty ShowAlbumTextProperty = DependencyProperty.Register("ShowAlbumText", 
                        typeof(bool),
                        typeof(PlaylistControl),
                        new PropertyMetadata(true));

ShowAlbumTextPlaylistControl的xaml中的ListView.ItemTemplate中这样使用:

<ListView>
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="data:Music">
            <local:PlaylistControlItem DataContext="{x:Bind}" ShowAlbumText="{Binding ShowAlbumText}">
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

但是,这个Binding报错

Error: BindingExpression path error: 'ShowAlbumText' property not found on 'SMPlayer.Models.Music'. BindingExpression: Path='ShowAlbumText' DataItem='SMPlayer.Models.Music'; target element is 'SMPlayer.Controls.PlaylistControlItem' (Name='null'); target property is 'ShowAlbumText' (type 'Boolean')

那么如何将 ShowAlbumText 绑定到 PlaylistControlItem?我明白 ShowAlbumText 不是 Music 的 属性 (Music 是我的视图模型)。这是我 UserControlDependencyProperty。一个更一般的问题,如何将 UserControl 中的 DependencyPropertyItemsSource 中的 ViewModel 绑定到 DataTemplate?

来源XAML.

来源Csharp Code.

您可以使用 ElementName 将绑定点指向 XAML 中元素的 属性,而不是数据上下文的 属性。在您的情况下,您希望该元素是 UserControl/PlaylistControl.

为 UserControl 元素命名:

<UserControl x:Class="WhateverYourNamespaceIs.PlaylistControl"
    ...
    x:Name="Foo">

将您的绑定指向具有该名称的元素:

<local:PlaylistControlItem DataContext="{x:Bind}" ShowAlbumText="{Binding ElementName=Foo, Path=ShowAlbumText}">

为您的页面命名,其中包含列表视图,如下所示

<Page
    x:Class="TestUwpApp.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TestUwpApp"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
    Name="MainPageName">

然后像这样绑定属性"ShowAlbumText"。

<ListView>
<ListView.ItemTemplate>
    <DataTemplate x:DataType="data:Music">
        <local:PlaylistControlItem DataContext="{x:Bind}" ShowAlbumText="{Binding ElementName=MainPageName,Path=DataContext.ShowAlbumText}">
    </DataTemplate>
</ListView.ItemTemplate>