【问题标题】:How to set TemplateBinding to resolve WPF error "Cannot set a TemplateBinding if not in a template."?如何设置 TemplateBinding 以解决 WPF 错误“如果不在模板中,则无法设置 TemplateBinding。”?
【发布时间】:2012-04-04 13:07:22
【问题描述】:

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

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.

我该如何解决这个问题?

【问题讨论】:

    标签: wpf templatebinding


    【解决方案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>
    

    【讨论】:

      【解决方案2】:

      问题是你没有模板。您的 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> 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多