How to set TemplateBinding to resolve WPF error “Cannot set a TemplateBinding if not in a template.”?

StackOverflow https://stackoverflow.com/questions/10011747

  •  29-05-2021
  •  | 
  •  

Question

I'm trying to implement the example outlined here:

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

The author states "The ContentPresenter control can be used to display the content of a WPF control."

with the following code:

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

I've added it to my window as follows:

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

But I'm getting the following error:

Cannot set a TemplateBinding if not in a template.

How can I resolve this?

Was it helpful?

Solution

You need to put the ContentPresent in the ControlTemplate, like that

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

OTHER TIPS

The problem is that you have no template. Your XAML should look somehow like this:

<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> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top