user4758246
user4758246

Reputation: 585

WPF: Button wont change its Grid.Column

I want to create a Menu with a Button on the right and one on the left. In the center of the Menu i want a MenuItem. Everything works so far except for the Button_forward which i want to put in GridColumn 2. No matter what i try, the Button stays in GridColumn 0. I can display everything in GridColumn 2 except that Button.

This is what it's supposed to look lik

+------------------------------------+
| Button | MenuItem | Button |
+------------------------------------+

<Menu DockPanel.Dock="Bottom" Height="30" Background="Gainsboro" HorizontalAlignment="Stretch">
    <Menu.ItemsPanel>
         <ItemsPanelTemplate>
                <Grid ShowGridLines="True" x:Name="Grid1">        
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="Auto"/>
                    </Grid.ColumnDefinitions>
                </Grid>
        </ItemsPanelTemplate>
    </Menu.ItemsPanel>
    <Button Height="20"  Width="40" Grid.Column="0" x:Name="Button_backward"     Click="Button_backward_Click" IsEnabled="False">
        <Image Source="..\Resources\leftarrow.png"/>
    </Button>

    <MenuItem Grid.Column="1" Height="20" >
         <TextBox Text="Test"></TextBox>
    </MenuItem>
    <Button Grid.Column="2" Height="20"  Width="40" x:Name="Button_forward" Click="Button_forward_Click" IsEnabled="False">
        <Image Source="..\Resources\rightarrow.png"/>
    </Button>
    </Menu>

If i put the Button in a MenuItem, it is displayed correctly in Column 2

    <MenuItem Grid.Column="2">
        <Button Height="20"  Width="40" x:Name="Button_forward" Click="Button_forward_Click" IsEnabled="False">
            <Image Source="..\Resources\rightarrow.png"/>
        </Button>
    </MenuItem>    

How can i display the Button in the second column?

Thanks!

Upvotes: 2

Views: 196

Answers (1)

Viv
Viv

Reputation: 17398

Well this is understandable,

The way the Menu control works is if you do not provide a MenuItem and provide something like a Button directly, it will wrap that Button in a MenuItem internally(thus making your Grid.Column specification on the Button useless as far as the menu's ItemsPanel is concerned).

You can check this behavior with Snoop such as:

As you can see the Button is wrapped in a MenuItem and since it does not have a Grid.Column specified on it, it gets placed at column 0 as default thus giving you your issue.

Solution:

As you guessed, wrap your Button in a MenuItem (thus giving it the appropriate column in the definition which the system wont change later)

or

Style a MenuItem to look like your Button and use that directly.

or

Use a different Layout control like StackPanel or sorts that don't impose this requirement

Upvotes: 2

Related Questions