WPF如何在介面上顯示訊息框,自動滾動,非同步操作等
WPF訊息列表動態顯示模型
public class ListMessageModel : 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"));
}
}
public void AddItemsToStatus(string strStatus)
{
if (listStatus.Count > 1000)
{
listStatus.RemoveAt(0);
}
ListStatus.Add(strStatus);
FocusLastItem();
}
/// <summary>
/// 委託定義,用於控制介面元素
/// </summary>
public delegate void ScrollToEnd();
public ScrollToEnd FocusLastItem = null;
}
介面繫結如下
<ListBox x:Name="ListBoxMessage" ItemsSource="{Binding ListStatus}"></ListBox>
介面後臺初始化關鍵資訊
public void InitData()
{
vm = new ListMessageModel();
ListBoxMessage.DataContext = vm;
vm.FocusLastItem += AutoScroll;
//業務相關此處可以調整為依賴注入
read = new DeviceClass.DllDevice.ReadCarder.VD67S_ReadWriteCarder();
DataContext = read;
}
/// <summary>
///
/// </summary>
public void AddLogAction()
{
//業務日誌相關,顯示內容有可能是非同步執行緒
read.AddLogAction(new Action<string>((a) =>
{
this.Dispatcher.BeginInvoke(new Action(() =>
{
vm.AddItemsToStatus(a);
}), DispatcherPriority.Background, null);
}));
}
/// <summary>
/// 滾動條自動滾動
/// </summary>
private void AutoScroll()
{
if (ListBoxMessage.Items.Count > 0)
{
ListBoxMessage.ScrollIntoView(ListBoxMessage.Items[ListBoxMessage.Items.Count - 1]);
}
}