欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

WPF ListView 实时更新数据

最编程 2024-10-09 07:07:23
...
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; 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.Navigation; using System.Windows.Shapes; namespace TestListView { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { private static ObservableCollection<UserData> List1 = new ObservableCollection<UserData>(); public MainWindow() { InitializeComponent(); UserList.ItemsSource = List1; } private void Button_Click(object sender, RoutedEventArgs e) { Task.Run(() => { while (true) { UserList.Dispatcher.Invoke(new Action(() => { List1 = UserData.GettestDate(); UserList.ItemsSource = List1; })); Thread.Sleep(2000); } }); } } class UserData : INotifyPropertyChanged //通知接口 { public event PropertyChangedEventHandler PropertyChanged; private string _NameLt; private bool _StatueLt; public string NameLt { get { return _NameLt; } set { _NameLt = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("NameLt")); } } public bool StatueLt { get { return _StatueLt; } set { _StatueLt = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("StatueLt")); } } public UserData() { _StatueLt = StatueLt; _NameLt = NameLt; } public static ObservableCollection<UserData> GettestDate() { ObservableCollection<UserData> oneSources = new ObservableCollection<UserData>(); for (int i = 0; i < 5; i++) { var random = new Random(); oneSources.Add(new UserData() { NameLt = DateTime.Now.ToString(), StatueLt = random.NextDouble() >= 0.5 }); Thread.Sleep(200); } return oneSources; } } }

推荐阅读