2012-04-04 6 views
1

私はここで説明する例を実装しようとしています:WPFエラーを解決するためにTemplateBindingを設定する方法 "テンプレートにない場合はTemplateBindingを設定できません。"

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. 

をどうすれば解決できますか?

答えて

1

あなたはその

<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> 
0

のような問題は、あなたが何のテンプレートを持っていないということです、ControlTemplateの中ContentPresentを配置する必要があります。 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> 
関連する問題