0

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

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

我确定我错过了一些东西......我不知道它是什么......

代码示例如下:

该类目前非常简单:

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

谢谢,

亚当

4

2 回答 2

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>
于 2009-08-21T14:59:00.270 回答
0

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

于 2009-08-21T14:39:46.557 回答