Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size-to-content-layout problem in WPF

Tags:

layout

wpf

This is supposed to be a no brainer but I still can’t figure it out.

In my sample app there’s a button and a textbox in a dockpanel. If the content of the textbox is smaller than the content of the textbox the window is as big as it needs to be to display the content of the button. That’s what I want. But if I put more text into the textbox the window gets wider :-(

The behavior I want is that the window gets the width according to the buttons content and the textbox wraps its content (or/and shows scrollbars if necessary).

Thank you!

Some sample code:

<Window x:Class="SO1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" SizeToContent="Width" FontSize="20">
    <DockPanel>
        <Button DockPanel.Dock="Top">A rather long text</Button>
        <TextBlock TextWrapping="Wrap">Short text</TextBlock>
    </DockPanel>
</Window>
like image 639
Alex Janzik Avatar asked Oct 29 '08 08:10

Alex Janzik


1 Answers

Having tried it, it seems that binding the TextBlock's MaxWidth to the ActualWidth of the Button achieves the effect you're after:

<Button x:Name="btn" DockPanel.Dock="Top">Short text</Button>
<TextBlock TextWrapping="Wrap" 
  MaxWidth="{Binding ElementName=btn,Path=ActualWidth}">A rather long text</TextBlock>
like image 126
Matt Hamilton Avatar answered Oct 26 '22 10:10

Matt Hamilton