2012-04-04 33 views
1

我試圖實現在此列出的例子:如何設置TemplateBinding以解決WPF錯誤「如果不在模板中,則無法設置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

你需要把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> 
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> 
相關問題