using Autodesk.Revit.DB; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EncapsulationProgressBar.ViewModels { internal class ProgressMonitorViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private bool Cancel { get; set; } public string ProcessTitle { get; set; } public int MaxValue { get; set; } = 10; public int CurrentValue { get; set; } = 0; public string CurrentContext { get; set; } = string.Empty; private Views.ProgressMonitorView ProgressView { get; set; } private delegate void ProgressBarDelegate(); public Action Action { get; set; } private Document doc; public ProgressMonitorViewModel(Document doc ) { this.doc = doc; } public void ProgressModal() { ProgressView = new Views.ProgressMonitorView(); ProgressView.DataContext = this; ProgressView.Closed += CurrentUI_Closed; ProgressView.ContentRendered += ProgressEvent; ProgressView.ShowDialog(); } private void ProgressEvent(object sender, EventArgs e) { ProgressView.ContentRendered -= ProgressEvent; #region 先决条件判断 //Parameter parameter = CurrentWall.get_Parameter(BuiltInParameter.DOOR_NUMBER); //if (parameter.IsReadOnly) //{ // CloseWindow(); // throw new Exception("Mark parameter is read only"); //} #endregion #region 处理内容 using (Transaction t = new Transaction(doc, ProcessTitle)) { t.Start(); for (CurrentValue = 0; CurrentValue <= MaxValue; ++CurrentValue) { if (Cancel) break; CurrentContext = string.Format("正在处理 {0} of {1} ", CurrentValue+1, MaxValue); ProgressView.Dispatcher.Invoke(new ProgressBarDelegate(NotifyUI), System.Windows.Threading.DispatcherPriority.Background); #region DoSomething try { Action(CurrentValue); //parameter.Set(CurrentViewModel.CurrentValue.ToString()); } catch { CloseWindow(); throw new Exception("处理失败"); } System.Threading.Thread.Sleep(50); #endregion DoSomething //CurrentContext = string.Format("处理完成 {0} of {1} ", CurrentValue, MaxValue); //ProgressView.Dispatcher.Invoke(new ProgressBarDelegate(NotifyUI), System.Windows.Threading.DispatcherPriority.Background); } t.Commit(); } #endregion CloseWindow(); } public void NotifyUI() { Type classType = this.GetType(); if (classType != null) { System.Reflection.PropertyInfo[] currentProperties = classType.GetProperties(); foreach (System.Reflection.PropertyInfo currentProperty in currentProperties) OnPropertyChanged(currentProperty.Name); } } private void OnPropertyChanged(string targetProperty) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(targetProperty)); } private void CloseWindow() { ProgressView.Closed -= CurrentUI_Closed; ProgressView.Close(); } private void CurrentUI_Closed(object sender, EventArgs e) { Cancel = true; } } }