我正在尝试实施此处列出的示例:
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.
我该如何解决这个问题?
答案 0 :(得分: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>
答案 1 :(得分: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>