1

我正在尝试实现此处概述的示例:

http://www.codeproject.com/Articles/30994/Introduction-to-WPF-Templates

作者声明“该ContentPresenter控件可用于显示 WPF 控件的内容。”

使用以下代码:

<ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" 
Content="{TemplateBinding Button.Content}" />

我已将其添加到我的窗口中,如下所示:

<Window x:Class="HKC.Desktop.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="487" Width="765.924" Loaded="Window_Loaded">

    <Grid x:Name="mainGrid" Background="#FF252525">
        <Button Content="Push Me" Template="{StaticResource buttonTemplate}" Name="button1" Height="100" Width="100"></Button>

        <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center"  Content="{TemplateBinding Button.Content}" />
    </Grid>


</Window>

但我收到以下错误:

Cannot set a TemplateBinding if not in a template.

我该如何解决这个问题?

4

2 回答 2

1

您需要将 ContentPresent 放在 ControlTemplate 中,就像这样

<ControlTemplate x:Key="buttonTemplate" TargetType="{x:Type Button}">
            <Grid>
                <Ellipse Name="el1" Fill="Orange" Width="100" Height="100">
                </Ellipse>
                <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" 
                        Content="{TemplateBinding Button.Content}" />
            </Grid>
</ControlTemplate>
于 2012-04-04T13:23:38.697 回答
0

问题是你没有模板。您的 XAML 应该看起来像这样:

<Window x:Class="HKC.Desktop.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" Height="487" Width="765.924" Loaded="Window_Loaded">
    <Window.Resources>
        <ControlTemplate x:Key="buttonTemplate" TargetType="{x:Type Button}">      
            <Ellipse Name="el1" Fill="Orange" Width="100" Height="100">            
            <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" Content="{TemplateBinding Button.Content}" /> 
        </ControlTemplate>
    </Window.Resources> 

    <Grid x:Name="mainGrid" Background="#FF252525"> 
        <Button Content="Push Me" Template="{StaticResource buttonTemplate}" Name="button1" Height="100" Width="100"/>  
    </Grid> 
</Window> 
于 2012-04-04T13:24:25.670 回答