ListView 設置SelectedIndex屬性不會滾動界面,只能通過ScrollIntoView方法設置,所以使用觸發(fā)器檢測
SelectedIndex ,使用擴展屬性定義SelectedIndex的行為文章來源:http://www.zghlxwxcb.cn/news/detail-625512.html
引入dll
手動引入 System.Windows.Interactivity Microsoft.Expression.Interactions
xmal中添加聲明文章來源地址http://www.zghlxwxcb.cn/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);
}
}
定義數(shù)據(jù)觸發(fā)器
<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模式下數(shù)據(jù)增加自動滾動到底部的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!