一、绑定
ListBox绑定ViewModel中的string链表,注意不能用普通的List<string>,需要定义ObservableCollection<string>(如果用List<string>,界面刷新会有所延迟)
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(this, e); } private ObservableCollection<string> listStatus = new ObservableCollection<string> { }; public ObservableCollection<string> ListStatus { get { return listStatus; } set { listStatus = value; OnPropertyChanged(new PropertyChangedEventArgs("ListStatus")); } } } }