如何正确设置此按钮与父 ListView ItemsControl 的绑定?

How do I properly set this button's binding to the parent ListView ItemsControl?

我在 ListView ItemTemplate 中设置了一个自定义按钮。 Listview 的 ItemSource 绑定到项目集合,非常标准。我在列表视图中也有一些标签,除按钮外一切正常。

使用 {Binding buttonName} 将按钮绑定到其中一个属性根本不起作用,但如果我使用 {Binding Items/buttonName, ElementName=listView} 它会起作用 - 唯一的问题是,当我这样做时这样,该 listView 中的每个按钮都将具有完全相同的按钮名称。

现在的问题源于我的自定义按钮的 DataContext 被设置为 Self;不幸的是,它必须设置为 Self,因为我使用的自定义样式需要它。如果我尝试将按钮更改为 UserControl(将按钮作为子按钮,并在其上设置 DataContext),则出于某种原因我无法使用按钮的命令 属性。

这是我的 ListView 使用自定义按钮的简化版本:

<ListView x:Name="listView" ItemsSource="{Binding MyPeopleData}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Label Content="{Binding PersonName}"/>
                <ct:RevealButton Content="{Binding Items/recommendation, ElementName=listView}"/>
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

正如我上面所说,这将使列表视图中的每个项目都使用相同的 recommendation 属性 而不是使用它自己的项目。 如果我尝试使用

<ct:RevealButton Content="{Binding recommendation}"/> 

它只是行不通,考虑到自定义按钮的 DataContext,这是有道理的,如下所示:

<Button x:Class="RevealButton" Width="{Binding Width}" Height="{Binding Height}" Background="{Binding ButtonBackground}" DataContext="{Binding RelativeSource={RelativeSource Self}}" Style="{DynamicResource ButtonRevealStyleC}" mc:Ignorable="d">
    <Button.ContentTemplate>
        <DataTemplate>
            <ContentPresenter Content="{TemplateBinding Content}" />
        </DataTemplate>
    </Button.ContentTemplate>

</Button>

所以这最终成为 XY Problem。因为我使用的修改后的样式绑定不佳 属性,所以当父控件没有将 DataContext 设置为 self 时它会失败。 原来是这样:

<SolidColorBrush Opacity="0.8" Color="{Binding ButtonBackground.Color}" />

并且 ButtonBackground 是我的自定义 Button 公开的依赖项 属性,因此以这种方式绑定样式意味着它仅在 Button 的上下文本身时才有效。将其更改为:

<SolidColorBrush Opacity="0.8" Color="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ButtonBackground.Color}" />

修复了 DataContext 依赖项,进而修复了上述问题的层次结构。