【问题标题】:TemplateBinding not working with .NET framework objectsTemplateBinding 不适用于 .NET 框架对象
【发布时间】:2009-08-21 14:33:04
【问题描述】:

我不熟悉使用ControlTemplate。我正在编写我的第一个控件,但我遇到了(在我看来)一个非常奇怪的问题。

我使TemplateBinding 工作的任何依赖属性,但来自 .NET 框架对象的任何属性,即ContentControlContent 属性或ItemsControlItems 属性不会被填充在运行时。

我确定我错过了什么……我不知道是什么……

代码示例如下:

目前这个类很简单:

public class Title : ContentControl
{
}

模板是:

<Style TargetType="{x:Type UI:Title}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type UI:Title}">
                <TextBlock Text="{TemplateBinding Content}" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

ContentControl 基类是位于 System.Windows.Controls.Control 命名空间中的 .NET 类。

谢谢,

亚当

【问题讨论】:

  • 你能添加一个代码 sn-p 来显示什么不起作用吗?
  • 很抱歉。我现在加了一个。谢谢。

标签: wpf controltemplate templatebinding


【解决方案1】:

我相信,如果您想覆盖 Content 的放置位置,您可以使用 ContentPresenter 来做到这一点。

<Style TargetType="{x:Type UI:Title}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type UI:Title}">
                <Label>
                    <ContentPresenter />
                </Label>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

注意,我还从 TextBlock 更改为 Label,因为我相信 TextBlock.Text 属性不会接受来自 ContentControl.Content 的所有内容。这是我整理的一个按预期工作的示例:

<Window x:Class="ContentControlTest.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:ContentControlTest"
        Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <Style TargetType="{x:Type local:Title}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type local:Title}">
                        <Button>
                            <ContentPresenter />
                        </Button>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <local:Title>
        <TextBlock Text="Happy Days!" />
    </local:Title>
</Window>

【讨论】:

  • 我刚刚尝试了您的建议。它似乎不起作用......我做了更多调查,似乎无论我何时设置属性它都不会显示,但如果我在 Title 类的构造函数中放置一个值,则为内容属性然后显示...
  • 有什么想法吗?感谢您的反馈。
  • 这不违反自己制作控件的规则吗?据我了解,我不应该将任何控件放在我的窗口上,因为 General.xaml 中定义的样式将处理它。我想将 TemplateBind 绑定到 Title 类的 Content 属性,因此每当该属性发生更改时,它都会在我的 UI 中更新。再次感谢您的反馈。
  • 那么您真正想要的是将标题控件的内容绑定到某个文本值吗?在这种情况下,TemplateBinding 也不是您要寻找的。​​span>
  • 已经有一段时间了,我正在清理。是的你是对的。在这种情况下,模板绑定不是我要寻找的。由于它是一个内容控件,我可以使用内容演示器来显示内容属性值,如示例代码中所示。感谢您的帮助。
【解决方案2】:

您可能需要在对象上实现 INotifyPropertyChanged 接口,并在集合上实现 INotifyCollectionChanged。

【讨论】:

    猜你喜欢
    • 2014-01-28
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 2012-08-21
    • 2018-05-04
    相关资源
    最近更新 更多