0

In the following code, I create a ComboBox of width 120. I then bind the width of the enclosing StackPanel to the width of this ComboBox. Finally, I bind the Width property of the main widow to the width of the StackPanel.

<Window x:Name="window" x:Class="ExampleApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ExampleApp"
        mc:Ignorable="d"
        Title="MainWindow" Height="110" Width="{Binding Width, ElementName=stackPanel}" HorizontalAlignment="Left" VerticalAlignment="Top">
   <StackPanel x:Name="stackPanel" HorizontalAlignment="Left" Width="{Binding Width, ElementName=comboBox}" VerticalAlignment="Top" Height="90">
      <ComboBox x:Name="comboBox" Width="120" HorizontalAlignment="Left"/>
      <CheckBox Content="First Item"/>
      <CheckBox Content="Second Item"/>
      <CheckBox Content="Third Item"/>
      <TextBlock TextWrapping="Wrap" Text="TextBlock"/>
   </StackPanel>
</Window>

Unfortunately, my window looks like this:

enter image description here

What am I doing wrong and why is the main window width not snapping to the ComboBox width as I intend?

user32882
  • 5,094
  • 5
  • 43
  • 82

2 Answers2

0

You don't need to bind the window height and width to the stack panel. You can use a window's SizeToContent property.

Lukasz Szczygielek
  • 2,768
  • 2
  • 20
  • 34
0

Try adding Mode=TwoWay Width="{Binding Width, ElementName=stackPanel, Mode=TwoWay}"

To why Mode=TwoWay check this out: https://stackoverflow.com/a/2305234

Or use SizeToContent="Width" on window, like Lukasz Szczygielek told.

Sheriff
  • 69
  • 4