今天,一个朋友问题listview如何实现动态加载数据(他的使用需求是:在滚动到listview最下一行时,继续加载之后的数据)。
我尝试了一下,没有找到相关的事件。为了给出一个可能的解决方案,于是想出以下的方法:
主要思路:
1.监听listview最后一个元素的距离,假定listView最后一个选项叫 listViewItem_last, 其 纵向偏移为 D_y。
2.因listview每次滚动,滚动高度都是listviewitem的高度,所以设置定位相对方便。
3.当最后一个listViewItem_last的y向偏移 D_y 增大时,则表示滚动条下拉了。如果D_y 接近于 listView 的高度,则表示只是需要给给数据源添加数据(需要显示下一页的内容了)
以下是xaml 及 cs代码:
<Window x:Class="CardPost.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="436" Width="807">
<Grid>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="47,40,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<ListView Height="373" HorizontalAlignment="Left" Margin="176,12,0,0" Name="listView1" VerticalAlignment="Top" Width="597" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="12,131,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="12,0,0,184" Name="textBox2" VerticalAlignment="Bottom" Width="120" />
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
namespace CardPost
{
public partial class Window1 : Window
{
private Thread myMonitorThread;
public Window1()
{
InitializeComponent();
StartThread();
}
public void StartThread()
{
myMonitorThread = new Thread(new ParameterizedThreadStart(MonitorMethod));
myMonitorThread.Start();
}
private void MonitorMethod(object obj)
{
while (true)
{
this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(() =>
{
textBox1.Text = listView1.Height.ToString();
int count = listView1.Items.Count;
textBox2.Text = (100 * count).ToString();
if (count >= 1)
{
ListViewItem lvi = listView1.Items[count - 1] as ListViewItem;
Point point = lvi.TranslatePoint(new Point(), listView1);
Console.WriteLine(String.Format("({0},{1}", point.X, point.Y));
}
}));
Thread.Sleep(100);
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
for(int i =0;i<9;i++)
{
ListViewItem lvi = new ListViewItem();
lvi.Width = 100;
lvi.Height = 100;
Border border = new Border();
border.Width = 100;
border.Height = 90;
border.Background = Brushes.Gray;
border.Margin = new Thickness(0, 5, 0, 5);
border.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
lvi.Content = border;
listView1.Items.Add(lvi);
}
}
}
}