WPF技巧20190722 LIstbox/ListView 自动流动到数据最后一行
一.需求:
我们在利用ListView或者ListBox来显示不断增加的数据时,总是希望能看到最新增加到行尾的一行最新数据。实现这个需求,使用传统的方式并不难,而使用MVVM模式进行数据绑定实现,就要依靠为控件增加附加属性的方法来实现.
二. 实现方式
1. 实现方式一
(摘自网页,原文标题:WPF ListBox如何实现动态加载数据,并且滚动条自动下拉)
WPF ListBox如何实现动态加载数据,并且滚动条自动下拉
1.1 绑定
ListBox绑定ViewModel中的string链表,注意不能用普通的List,需要定义ObservableCollection(如果用List,界面刷新会有所延迟)
XAML(DataContext为viewModel):
<ListBox x:Name="StatusList" ItemsSource="{Binding ListStatus}" />
ViewModel:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Windows.Controls;
using System.IO;
using System.IO.Ports;
using System.Data;
using System.Windows.Threading;
namespace SPT
{
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(