Reputation: 2385
I am trying to reverse the order of which the children appear in the StackPanel. I want to be able to add new children (whilst running the app) to the top of the list instead of the bottom. I have tried using various XAML code but nothing worked.
What is the easiest way to do this?
Upvotes: 3
Views: 4094
Reputation: 6830
I've found a way to stack elements in opposite order than they are listed as children using a DockPanel
. This should allow you do what you want entirely in XAML (no need for code-behind). This could be helpful if you're binding to a collection and you don't want to reverse the order of the collection or don't want to insert items at the head of the collection.
When you specify the Dock
attached property on multiple child element (e.g. DockPanel.Dock="Bottom"
) it will stack them on the specified edge of the panel in order, such that the first child element will be closest that edge.
Therefore, to stack elements bottom-to-top, set the Dock
property to Bottom
on all the child elements and give them a fixed height. Here's an example:
<UserControl x:Class="UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" d:DesignHeight="200" d:DesignWidth="200">
<DockPanel LastChildFill="False">
<Button DockPanel.Dock="Bottom" Height="40" Content="B 1" />
<Button DockPanel.Dock="Bottom" Height="40" Content="B 2" />
<Button DockPanel.Dock="Bottom" Height="40" Content="B 3" />
</DockPanel>
</UserControl>
Note the use of LastChildFill="False"
- by default the DockPanel
will stretch the last item to fill the remaining space.
This renders as follows:
The same also works for right-to-left ordering of elements
<UserControl x:Class="DigitalElectronics.UI.Controls.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" d:DesignHeight="200" d:DesignWidth="200">
<DockPanel LastChildFill="False">
<Button DockPanel.Dock="Right" Width="40" Content="B 1" />
<Button DockPanel.Dock="Right" Width="40" Content="B 2" />
<Button DockPanel.Dock="Right" Width="40" Content="B 3" />
</DockPanel>
</UserControl>
Upvotes: 2