skq*_*ada 5 wpf listview scroll
我有一个ListView绑定到一个可观察的集合.当项目添加到可观察集合时,列表视图不会自动滚动以显示最近添加的项目.我试图坚持良好的WPF实践,并希望避免在视图的代码隐藏中编写任何代码.有没有一种简单的方法可以通过XAML或相应的Model的代码实现这一目的?
<ListView HorizontalAlignment="Center" ItemsSource="{Binding ScenarioSnippets}" Background="{x:Null}"
BorderBrush="{x:Null}" BorderThickness="0" SelectionMode="Single" VerticalAlignment="Top"
HorizontalContentAlignment="Center" IsSynchronizedWithCurrentItem="True">
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Focusable" Value="False" />
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView Selector.IsSelected="True" AllowsColumnReorder="False">
<GridView.Columns>
<GridViewColumn CellTemplate="{StaticResource ScenarioSnippetItemCellTemplate}"
HeaderContainerStyle="{StaticResource GridViewHeaderStyle}" />
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
Run Code Online (Sandbox Code Playgroud)
您可以使用混合行为:
public class AutoScrollToLastItemBehavior : Behavior<ListBox>
{
protected override void OnAttached()
{
base.OnAttached();
var collection = AssociatedObject.Items.SourceCollection as INotifyCollectionChanged;
if (collection != null)
collection.CollectionChanged += collection_CollectionChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
var collection = AssociatedObject.Items.SourceCollection as INotifyCollectionChanged;
if (collection != null)
collection.CollectionChanged -= collection_CollectionChanged;
}
private void collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
ScrollToLastItem();
}
}
private void ScrollToLastItem()
{
int count = AssociatedObject.Items.Count;
if (count > 0)
{
var last = AssociatedObject.Items[count - 1];
AssociatedObject.ScrollIntoView(last);
}
}
}
Run Code Online (Sandbox Code Playgroud)
XAML:
<ListView ItemsSource="...">
<i:Interaction.Behaviors>
<local:AutoScrollToLastItemBehavior />
</i:Interaction.Behaviors>
</ListView>
Run Code Online (Sandbox Code Playgroud)
(Behavior和Interaction类可以System.Windows.Interactivity.dll在Blend SDK中找到)
| 归档时间: |
|
| 查看次数: |
5276 次 |
| 最近记录: |