ListView 设置SelectedIndex属性不会滚动界面,只能通过ScrollIntoView方法设置,所以使用触发器检测
SelectedIndex ,使用扩展属性定义SelectedIndex的行为文章来源:https://www.toymoban.com/news/detail-625512.html
引入dll
手动引入 System.Windows.Interactivity Microsoft.Expression.Interactions
xmal中添加声明文章来源地址https://www.toymoban.com/news/detail-625512.html
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
定义扩展属性行为
public static class ScrollToSelectedBehavior
{
public static readonly DependencyProperty SelectedValueProperty = DependencyProperty.RegisterAttached(
"SelectedValue",
typeof(object),
typeof(ScrollToSelectedBehavior),
new PropertyMetadata(null, OnSelectedValueChange));
public static void SetSelectedValue(DependencyObject source, object value)
{
source.SetValue(SelectedValueProperty, value);
}
public static object GetSelectedValue(DependencyObject source)
{
return (object)source.GetValue(SelectedValueProperty);
}
private static void OnSelectedValueChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var listbox = d as ListBox;
listbox.ScrollIntoView(e.NewValue);
}
}
定义数据触发器
<i:Interaction.Triggers>
<ei:DataTrigger Binding="{Binding Items.Count, ElementName=list}" Comparison="NotEqual" Value="0">
<ei:ChangePropertyAction TargetName="list" PropertyName="SelectedIndex" Value="{Binding ElementName=list, Path=Items.Count}">
</ei:ChangePropertyAction>
</ei:DataTrigger>
</i:Interaction.Triggers>
测试
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:local="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="400">
<StackPanel Orientation="Vertical">
<ListView Height="200" ItemsSource="{Binding Itmes}" x:Name="list" local:ScrollToSelectedBehavior.SelectedValue="{Binding ElementName=list, Path=SelectedValue}" >
<i:Interaction.Triggers>
<ei:DataTrigger Binding="{Binding Items.Count, ElementName=list}" Comparison="NotEqual" Value="0">
<ei:ChangePropertyAction TargetName="list" PropertyName="SelectedIndex" Value="{Binding ElementName=list, Path=Items.Count}">
</ei:ChangePropertyAction>
</ei:DataTrigger>
</i:Interaction.Triggers>
</ListView>
<Button Width="75" Height="30" Click="Button_Click"> 新增</Button>
</StackPanel>
</Window>
到了这里,关于WPF ListView MVVM模式下数据增加自动滚动到底部的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!