Wednesday, August 18, 2010

WPF DockPanel and StatusBar Gotcha

I’ve only recently started to work with Windows Presentation Foundation (WPF) on an actual project. WPF is the new Microsoft technology for building powerful user interfaces.

I ran into this simple gotcha with the DockPanel control and thought I’d share. The issue was that my status bar would not dock properly at the bottom of the UI.

I wanted to add a toolbar, then some controls underneath that which are contained in a StackPanel control, and then the StatusBar control at the bottom. From an XML/HTML perspective, the following code made sense to me.

<DockPanel HorizontalAlignment="Stretch" Width="Auto" Height="Auto">
     <ToolBarTray HorizontalAlignment="Stretch" DockPanel.Dock="Top">
        <ToolBar Name="toolBarMain" Height="28" HorizontalAlignment="Stretch">
            …
        </ToolBar>
    </ToolBarTray>

    <StackPanel DockPanel.Dock="Top">
        <StackPanel Orientation="Horizontal">
            …
        </StackPanel>
    </StackPanel>
    <TabControl DockPanel.Dock="Left" TabStripPlacement="Bottom">
        …   
          </TabControl>

     <StatusBar DockPanel.Dock="Bottom" HorizontalAlignment="Stretch">
        <StatusBarItem>
            <TextBlock Text="Status..."/>
        </StatusBarItem>
    </StatusBar>
</DockPanel>

However, this didn’t work. The other controls messed up the StatusBar even though it was the only one set to dock to the bottom. The solution was to move the StatusBar all the way to the beginning of the DockPanel control. The reason this was happening makes sense to me now (for example, you might want the control on the left to go all the way to the bottom), but I assumed that if controls weren’t nested, then they wouldn’t affect one another.

<DockPanel HorizontalAlignment="Stretch" Width="Auto" Height="Auto">
    <StatusBar DockPanel.Dock="Bottom" HorizontalAlignment="Stretch">
        <StatusBarItem>
            <TextBlock Text="Status..."/>
        </StatusBarItem>
    </StatusBar>

    <ToolBarTray HorizontalAlignment="Stretch" DockPanel.Dock="Top">
        <ToolBar Name="toolBarMain" Height="28" HorizontalAlignment="Stretch”>
            …
        </ToolBar>
    </ToolBarTray>

    <StackPanel DockPanel.Dock="Top">
        <StackPanel Orientation="Horizontal">
            …
        </StackPanel>
    </StackPanel>
    <TabControl DockPanel.Dock="Left" TabStripPlacement="Bottom">
        …   
          </TabControl>
</DockPanel>

1 comment:

Anonymous said...

Very helpful.Thx