如何在自定义控件的样式中绑定一个附加属性?

问题描述 投票:0回答:1

我正在绑定一个自定义控件的高度(我们称它为 MyButton)到CustomControl的样式中的一个可继承的附加属性。

<Setter Property="Height" Value="{Binding (local:Element.IconContainerSize), RelativeSource={RelativeSource Self}}"/>

然而,这在设计器中和运行时都不起作用。只有当我在CustomControl的样式中设置Bindings时才会发生这种情况。当我在其容器的资源中设置绑定或在声明时将其显式设置为其高度时,它就会工作。

<StackPanel my:Element.IconContainerSize="18">
    <StackPanel.Resources>
        <Style TargetType="{x:Type cc:MyButton}">
            <!-- Works -->
            <Setter Property="Height" Value="{Binding (my:Element.IconContainerSize), RelativeSource={RelativeSource Self}}"/>
        </style>
    </StackPanel.Resources>
    <!-- Also works -->
    <cc:MyButton Height="{Binding (my:Element.IconContainerSize), RelativeSource={RelativeSource Self}}"/>

    <!-- Doesn't work (assuming the style above is removed in this case) -->
    <cc:MyButton />
</StackPanel>

UPDATE: 添加一个 Path= 之前所附的属性路径只在运行时工作,而不是在设计时工作,直到我手动重新加载解决方案。当我在项目中编辑某些内容时,我无法在设计时使其工作,就在我为CustomControl库重建项目之后。

c# wpf data-binding attached-properties
1个回答
0
投票

尝试在绑定中设置Path。{Binding Path=(my:Element.IconContainerSize), RelativeSource={RelativeSource Self}}。 代码相同,但有时会有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.