首页 > 解决方案 > 如何绑定到自定义控件样式内的附加属性?

问题描述

我将 CustomControl(我们称之为MyButton)的高度绑定到 CustomControl 样式内的可继承附加属性:

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

但是,这在设计器和我运行它时都不起作用。仅当我在 CustomControl 的样式中设置绑定时才会发生这种情况。当我在其容器的资源中设置绑定或在声明时将其显式设置为其高度时,它可以工作:

<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>


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

标签: c#wpfdata-bindingattached-properties

解决方案


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


推荐阅读