Reputation: 71
I have searched and searched and all I see are XAML
examples. I want to do this programmatically without XAML
. Here is the code:
StackPanel stackPanel = new StackPanel();
stackPanel.Orientation = Orientation.Horizontal;
lstBox.Items.Add(stackPanel);
mainGrid.Children.Add(lstBox);`
This does not work since the list remains vertical. I tried making the Listbox
a child of the StackPanel
and other combinations unsuccessfully.
Upvotes: 1
Views: 349
Reputation: 388
For an horizontal panel it's better to use a WrapPanel to take benefits of the wrapping elements. Here is an example for the new year ;-)
XAML
<Grid>
<ScrollViewer HorizontalAlignment="Left" Width="280" Height="99" Margin="36,159,0,0" VerticalAlignment="Top" >
<WrapPanel x:Name="Wrappanel1" HorizontalAlignment="Left"/>
</ScrollViewer>
</Grid>
C#
public MainWindow()
{
InitializeComponent();
additem(Brushes.Orange,"Hello");
additem(Brushes.Green,"World");
additem(Brushes.DarkOrchid,"and");
additem(Brushes.RoyalBlue,"Happy");
additem(Brushes.Orange, "new");
additem(Brushes.SteelBlue, "Year");
additem(Brushes.RoyalBlue, "for");
additem(Brushes.Green, "2020");
additem(Brushes.Orange, "All");
additem(Brushes.DarkOrchid, "the");
additem(Brushes.Orange, "best");
}
private void additem(SolidColorBrush BackgroundColor,string information)
{
Button but = new Button();
but.Height = 50;
but.Content = information;
but.Background = BackgroundColor;
but.FontSize = 18;
Wrappanel1.Children.Add(but);
}
Upvotes: 1
Reputation: 8915
It is possible to set items panel horizontal in the following way too:
var wp = new FrameworkElementFactory(typeof(WrapPanel));
wp.SetValue(Panel.IsItemsHostProperty, true);
lstBox.ItemsPanel = new ItemsPanelTemplate(wp);
mainGrid.Children.Add(lstBox);
The WrapPanel might be used to keep together items like buttons in a toolbar control.
Upvotes: 1
Reputation: 169170
If you want the elements in the ListBox
to be displayed horizontally, you should set its ItemsPanel
property:
FrameworkElementFactory stackPanel = new FrameworkElementFactory(typeof(StackPanel));
stackPanel.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
lstBox.ItemsPanel = new ItemsPanelTemplate(stackPanel);
mainGrid.Children.Add(lstBox);
Upvotes: 3