If you want to switch the orientation of the WrapPanel between vertical and horizontal with the click of a button, you could try the following code. If I misunderstood, please let me know.
MainWindow.xaml:
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<DockPanel>
<ListBox x:Name="LB" Height="160" Width="90" DockPanel.Dock="Left" SelectionChanged="LB_SelectionChanged" >
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Background="AliceBlue" Orientation="Vertical" x:Name="WP" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Image Height="50" Width="50" Source="{Binding Path=UriSource}" Stretch="Fill" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
<Button x:Name="BTN_Rotation" Content="Dreh" Click="BTN_Rotation_Click" Grid.Row="1" />
</Grid>
MainWindow.xaml.cs:
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace ListBoxOrientationChangedPerClick
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
list.Add(new MyImage() { UriSource=@"6.jpg" });
list.Add(new MyImage() { UriSource=@"6.jpg" });
LB.ItemsSource = list;
}
ObservableCollection<MyImage> list=new ObservableCollection<MyImage>();
private T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
var child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is T)
return (T)child;
var childOfChild = FindVisualChild<T>(child);
if (childOfChild != null)
return childOfChild;
}
return null;
}
private void BTN_Rotation_Click(object sender, RoutedEventArgs e)
{
WrapPanel wrapPanel = FindVisualChild<WrapPanel>(LB);
if(wrapPanel.Orientation== Orientation.Horizontal)
{
wrapPanel.Orientation=Orientation.Vertical;
}
else
{
wrapPanel.Orientation = Orientation.Horizontal;
}
}
private void LB_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
public class MyImage : INotifyPropertyChanged
{
private string _img;
public string UriSource
{
get { return _img; }
set
{
_img = value;
NotifyPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
The result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread.
[5]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html