wpf listbox автоматический скролл вниз
У меня есть ListBox, я добавляю в него элементы, но с появлением скролла ListBox не опускается вниз, к добавляемому элементу, а отображает первые элементы; как сделать чтобы при добавлении элемента в ListBox он опускался вниз и были видны последние добавленные элементы?
(на всякий случай код)
<ListBox x:Name="ListBoxChessMoves"
Grid.Column="1" Margin="0 10 0 0"
ItemsSource="{Binding Moves}"
Background="LightSlateGray" HorizontalContentAlignment="Center">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock FontSize="25">
<Run Foreground="Blue" Text="{Binding NumberOfMove}"/>
<Run Foreground="White" Text="{Binding WhiteMove}"/>
<Run Foreground="Black" Text="{Binding BlackMove}"/>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsEnabled" Value="False"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
Ответы (1 шт):
Автор решения: Aarnihauta
→ Ссылка
В классе вашего окна MyWindow.xaml.cs:
public partial class MyWindow: Window
{
public MyWindow()
{
InitializeComponent();
((INotifyCollectionChanged)MyListBox.Items).CollectionChanged += Items_CollectionChanged;
}
private void Items_CollectionChanged (object? sender, EventArgs e)
{
Border border = (Border)VisualTreeHelper.GetChild(MyListBox, 0);
ScrollViewer scrollViewer = (ScrollViewer)VisualTreeHelper.GetChild(border, 0);
scrollViewer.ScrollToBottom();
}
}
Взял код вот из этого ответа, а так же комментария как добавить CollectionChanged для ListBox.Items.
Тип ItemCollection наследуется от CollectionView, который в свою очередь реализует INotifyCollectionChanged.
