【发布时间】:2013-05-03 10:11:29
【问题描述】:
我正在尝试在xaml 中创建自定义按钮。进展顺利,但我在内容对齐方面遇到了一些奇怪的问题。
如果我在"root grid" 中放置一个自定义按钮,则整个按钮都是可点击的,并且内容(按钮的文本)正确居中对齐。
但是,如果我以这种方式放置自定义按钮:
- 边框
- 堆栈面板
- 我的按钮
- 我的按钮
- 等等……
- 堆栈面板
然后,我的按钮 - 内容也正确居中,但只能点击内容的文本。不是整个按钮...
如果我将内容对齐设置为拉伸,它是可点击的,但文本不是居中的。
这是我的 xaml:如何在上述设置中使整个按钮可点击?
控制模板:
<ControlTemplate x:Key="ollema">
<Grid Background="{TemplateBinding Background}" VerticalAlignment="Stretch">
<Border Name="border"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<ContentPresenter Content="{TemplateBinding Property=ContentControl.Content}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
</ContentPresenter>
</StackPanel>
</Border>
</Grid>
</ControlTemplate>
我的主窗口中的 XAML:
<Border BorderBrush="White" BorderThickness="1" Margin="0" Width="200" Background="#FF00641E" HorizontalAlignment="Center" VerticalAlignment="Center">
<StackPanel Width="150" HorizontalAlignment="Center" VerticalAlignment="Center">
<ToggleButton Template="{StaticResource ollema}" Content="ToggleButton" Height="57" BorderBrush="White" Foreground="#FFE8E8E8" Background="{x:Null}" BorderThickness="0,0,0,1"/>
<ToggleButton Template="{StaticResource ollema}" Content="ToggleButton" Height="57" BorderBrush="White" Foreground="#FFE8E8E8" Background="{x:Null}" BorderThickness="0,0,0,1"/>
<ToggleButton Template="{StaticResource ollema}" Content="ToggleButton" Height="57" BorderBrush="White" Foreground="#FFE8E8E8" Background="{x:Null}" BorderThickness="0,0,0,1"/>
<ToggleButton Template="{StaticResource ollema}" Content="ToggleButton" Height="57" BorderBrush="White" Foreground="#FFE8E8E8" Background="{x:Null}" BorderThickness="0,0,0,1"/>
<ToggleButton Template="{StaticResource ollema}" Content="ToggleButton" Height="57" BorderBrush="White" Foreground="#FFE8E8E8" Background="{x:Null}" BorderThickness="0,0,0,1"/>
<ToggleButton Template="{StaticResource ollema}" Content="ToggleButton" Height="57" BorderBrush="{x:Null}" Foreground="#FFE8E8E8" Background="{x:Null}" BorderThickness="0"/>
</StackPanel>
</Border>
【问题讨论】:
-
这是
ControlTemplate本身的Button吗?如果是这样,将其中的ContentControl切换为ContentPresenter。并将Style设置为Background的默认Setter为Transparent,并将Background="{TemplateBinding Background}"添加到您的Grid。 -
@Viv 是的,这就是
ControlTemplate本身。我尝试了您提出的建议,但它给了我相同的结果。我认为这与我的buttons包含在stackpanel中而我的堆栈面板包含在border中有关。我再玩一会儿.. -
那么请您添加完整的 xaml 代码。我无法仅使用您发布的代码来重现这一点。样式、StackPanel 以及与此相关的 xaml 中的所有内容。
-
@Viv 谢谢,我编辑了我的帖子。请注意,我是 xaml 的新手...