【问题标题】:Binding to the TemplatedParent itself绑定到 TemplatedParent 本身
【发布时间】:2013-12-03 10:13:18
【问题描述】:

考虑一个自定义控件,在ResourceDictionary 中通过Style 定义ControlTemplate

<Style TargetType="{x:Type local:MyControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MyControl}">
                ....

在该模板的某些地方,我有一个 ContentControl,我想将其内容设置为 TemplatedParent 本身。

如果我将它绑定到 TemplatedParent 上的一个属性,效果会很好:

Content="{TemplateBinding LayoutMode}"

但是有没有办法将它绑定到TemplatedParent 本身?如果没有,是否有任何解决方法?

【问题讨论】:

    标签: c# wpf custom-controls controltemplate


    【解决方案1】:

    也许使用

    BoundProperty="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MyControl}}
    

    ?

    nb:如果您打算绑定“内容”属性来填充控件的“内容”(即可视子项),那将无法正常工作...

    【讨论】:

    • 这就是我正在尝试的,我想这就是它不起作用的原因,因为我得到了Logical tree depth exceeded while traversing the tree. This could indicate a cycle in the tree.
    • 即使它有效,您的模板父级已经在树中......您无法将其插入其他地方。您正在寻找的是 ContentPresenter,我猜...
    • ContentPresenter 工作!谢谢,那么ContentPresenterContentControl 有什么区别?
    • 简而言之,ContentPresenter 用于显示元素确定的运行时。它可以被视为一个占位符。见this post
    • 要了解更多,建议你反编译ContentControl.OnContentChanged和ContentPresenter.OnContentChanged。它们非常有趣:第一个调用 AddLogicalChild,而第二个不调用。 (因此没有使用 ContentPresenter 的逻辑循环)
    猜你喜欢
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多