【问题标题】:How to bind to an attached property inside the style of a custom control?如何绑定到自定义控件样式内的附加属性?
【发布时间】:2020-05-11 17:14:04
【问题描述】:

我将 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# wpf data-binding attached-properties


    【解决方案1】:

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

    【讨论】:

    • 它至少在我运行它时可以工作,但在我手动重新启动它之前它不会在设计器中更新。
    • 抱歉,我没有与 XAML 设计器合作的丰富经验,因此我无法向您提出任何建议。我只注意到一个讨论类似问题的线程:stackoverflow.com/questions/43429308/…。我不知道那里建议的解决方案是否可以帮助您。
    猜你喜欢
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 2011-06-24
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    相关资源
    最近更新 更多