当我将按钮的内容作为普通字符串时,例如<Button Content="Ok" />,按钮的行为就会正常。但是,如果我将内容更改为具有键盘加速器,例如<Button Content="_Ok" />,则按钮的样式会改变为具有不同的边距和大小。
我有一个没有键的TextBlock样式,所以它被应用到所有的TextBlocks中,我的问题是为什么当它的内容有一个加速器而不是它没有的时候它会被应用呢?
编辑:获取额外信息:默认样式在StackPanel的资源中,即按钮在其中。我想问题是,当按钮有加速器时,为什么不应用默认的TextBlock样式?
发布于 2010-10-06 18:37:26
WPF通过加速器向每个按钮(和菜单)添加一个TextBlock。
通过运行以下XAML可以看到这种效果(如果需要,请记住连接命令)。
考虑到问题的范围,解决问题的关键是将TextAlignment设置为TextBlock的值。如果您设置了TextBlock样式的宽度(我的行在下面注释掉了),文本将开始移动。添加HorizontalAlignment = Center还可以帮助TextBlock/Button中的文本居中,但这也会影响其他TextBlock控件。
<Window x:Class="ButtonAccelerator.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Main Window" Height="400" Width="800">
<Window.Resources>
<Style TargetType="TextBlock">
<!--<Setter Property="Width" Value="70"/>-->
<Setter Property="Height" Value="23"/>
<Setter Property="Background" Value="Pink"/>
<Setter Property="TextAlignment" Value="Center"/>
</Style>
<Style TargetType="Button">
<Setter Property="Width" Value="70"/>
<Setter Property="Height" Value="23"/>
</Style>
</Window.Resources>
<DockPanel>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel
Grid.Row="1" Grid.Column="1"
HorizontalAlignment="Right"
Orientation="Horizontal">
<TextBlock Text="OK" />
<Button
Content="OK"/>
<Button
Content="_OK"/>
</StackPanel>
</Grid>
</DockPanel>
</Window>发布于 2010-10-06 13:48:39
您应该使用斯诺普验证这一点,但是<Button Content="Ok" />会生成一个TextBlock来处理按钮中的文本。由于TextBlock不支持加速器密钥,所以我敢打赌,<Button Content="_Ok" />会导致它生成一个Label,因为Label会处理加速器密钥。
https://stackoverflow.com/questions/3872591
复制相似问题