Why does the style change when I add an accelerator to my button?

When I have the contents of a button as a regular string, for example. <Button Content="Ok" />then the button behaves as usual. But if I change the contents to have a keyboard accelerator, for example. <Button Content="_Ok" />The button style changes to different fields and sizes.

I have a TextBlock style that does not have a key, so it applies to all TextBlocks, my question is why it is applied when it has an accelerator, and not when it does not?

Change: . Additional information: the default style is inside the StackPanel resources, inside which there is a button. I think the question really is , why the default TextBlock style is not applied when the button has an accelerator?

+1
source share
2 answers

WPF adds a TextBlock to each button (and menu) using the accelerator.
You can see this effect by running the following XAML (remember to include the command if necessary).

The key to fixing the problem, given the size of your question, is to set the TextAlignment to Center for the TextBlock. If you set the Width style for a TextBlock (my line is commented below), the text will begin to shift. Adding HorizontalAlignment = Center also helps centralize the text in the TextBlock / Button, but it also affects other TextBlock controls.

<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>
+1
source

Snoop, <Button Content="Ok" /> TextBlock . TextBlock , , <Button Content="_Ok" /> Label , Label .

0

Source: https://habr.com/ru/post/1768820/


All Articles