首页 > 解决方案 > 有没有办法绑定到模板化控件的属性?

问题描述

我想将 ListViewItem 的背景颜色设置为 Item 的 DataTemplate 中使用的颜色。

这是 DataTemplate 之一,请注意设置的背景颜色:

<DataTemplate DataType="{x:Type viewmodel:DataPointViewModel}">
    <UniformGrid Columns="2" Background="LimeGreen">
        <TextBlock Text="{Binding Name}"/>
        <TextBlock Text="{Binding Description}"/>
    </UniformGrid>
</DataTemplate>

这是带有Border的ItemContainerStyle,设置为ListView的ItemContainerStyle:

<Style TargetType="{x:Type ListViewItem}">
    <Setter Property="Background" Value="Yellow"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListViewItem}">
                <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" 
                        Background="{TemplateBinding BackGround}">
                    <ContentPresenter/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

我想避免在 ViewModel 本身中有背景颜色。到目前为止,我所有的努力都导致了来自绑定的绑定错误,例如:

{Binding BackGround, RelativeSource={RelativeSource AncestorType=UniformGrid}}

将 Binding 设置为“TemplateBinding BackGround”后,它确实成功地使用了我在 Style 本身中设置的颜色,这正是我所期望的。

如何绑定到 DataTemplate 中的 BackGround 属性,或者这无法实现?

标签: wpfcontroltemplate

解决方案


推荐阅读