简体   繁体   中英

Fit WPF Label in User Control to the width of its Content

I have a WPF User Control that contains a simple label and rectangle on a grid, looking like this:

   <Grid x:Name="Pressbutton">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="14"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Rectangle x:Name="LayerColour" Grid.Column="0" Fill="#FFF4F4F5" Width="10" Height="10" Margin="0" Stroke="Black" VerticalAlignment="Center" MinWidth="10" MinHeight="10" Visibility="Visible" HorizontalAlignment="Center"/>
        <Label x:Name="DisplayNameLabel" Grid.Column="1" Content="Label"  Margin="0" VerticalAlignment="Center" Height="26" Visibility="Visible" />
    </Grid>

Then I am laying these out in a StackPanel, which works fine and using a GridSplitter to divide this list of labels from the other part of the window.

My window looks a little like this:

==========================================x
| StackPanel           |   Other Stuff    |
|    PressButton1      |                  |
|    PressButton2      |                  |
|    PressButton3      |                  |
===========================================

My problem is that currently the GridSplitter only wants to render in the centre of the Window, and I want the label list to be significantly more narrow. The ideal starting width for the label panel is as wide as the widest label.

I have tried measuring the ActualWidth of my User Controls but that is always being set to the width of the containing StackPanel. If I try and measure the width of the Labels those too seem determined to stretch to their maximum possible width. It seems ridiculous that I would have to go through the whole rigmarole of pre-rendering the text of my labels just to get an idea of how wide my labels are supposed to be when the text is right there on the label already, so I assume I am doing something wrong.

How do I find the width of the text on my label, so I can move the GridSplitter to fit the left pane snugly?

I assume based on your "drawing" that you have a Grid with two columns. You can set the first column to Auto width and place your stackpanel there. Set the second column to width 1*, create a GridSplitter and set its Grid.Column to 1, set a fixed width for it(i usually set it to 10) and set HorizontalAlignment to Left and VerticalAlignment to Stretch. Should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM