赞
踩
ListView 设置SelectedIndex属性不会滚动界面,只能通过ScrollIntoView方法设置,所以使用触发器检测
SelectedIndex ,使用扩展属性定义SelectedIndex的行为
手动引入 System.Windows.Interactivity Microsoft.Expression.Interactions
xmal中添加声明
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>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。