【发布时间】:2021-11-09 02:52:13
【问题描述】:
我试图弄清楚如何从单独的 ViewModel 更新进度对话框。这是我的第一个完整的 C# 应用程序,实际上,我的第一个应用程序。我已经在这个特定问题上停留了几天,并且觉得我已经尝试从几个不同的角度来处理它,但没有成功。
让我们从简要概述开始:我和我的团队将使用此应用程序来协助在现场部署 PC。它从一个非常简单的 UI 开始,登台技术将从列表中选择站点 ID,然后单击“配置”以启动该过程。该过程的其余部分不需要任何用户交互。
我正在尝试在初始 UI 顶部显示一个进度对话框,以向技术人员提供进度指示。
目前,我可以让进度框出现,但无法更新它。
ShellViewModel 的代码如下:
namespace StagingWpfUI.ViewModels
{
public class ShellViewModel : Conductor<object>, IHandle<ConfigureServerEvent>, IHandle<LoadDeviceInfoEvent>
{
#region Private Variables
private readonly IEventAggregator _events;
private readonly ProgressDialogViewModel _progressVM;
private readonly DeviceInfoViewModel _deviceInfoVM;
private readonly IWindowManager _window;
#endregion
#region Constructor
public ShellViewModel(IEventAggregator events,
IWindowManager window,
ProgressDialogViewModel progressVM,
DeviceInfoViewModel deviceInfoVM)
{
_events = events;
_progressVM = progressVM;
_deviceInfoVM = deviceInfoVM;
_window = window;
_events.SubscribeOnUIThread(this);
ActivateItemAsync(IoC.Get<DeviceConfigureViewModel>(), new CancellationToken());
}
#endregion
#region Public Methods
public async Task HandleAsync(ConfigureServerEvent message, CancellationToken cancellationToken)
{
//await ActivateItemAsync(_progress);
dynamic settings = new ExpandoObject();
settings.WindowStartupLocation = WindowStartupLocation.CenterOwner;
settings.ResizeMode = ResizeMode.NoResize;
settings.Title = "Progress";
settings.WindowStyle = WindowStyle.None;
await DeactivateItemAsync(IoC.Get<DeviceConfigureViewModel>(), true, new CancellationToken());
await _window.ShowWindowAsync(_progressVM, null, settings);
}
public async Task HandleAsync(LoadDeviceInfoEvent message, CancellationToken cancellationToken)
{
await DeactivateItemAsync(_deviceInfoVM, true);
}
#endregion
DeviceConfigureViewModel(主 UI)在应用程序启动时被激活。当从 DeviceConfigureVM 调用 ConfigureServer 方法时会调用 ProgressDialogVM。这很好用。但是当我尝试做任何工作时,进度不会更新。
这是 ProgressDialogView.xaml 的代码:
<UserControl x:Class="StagingWpfUI.Views.ProgressDialogView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"
mc:Ignorable="d" Background="LightBlue"
d:DesignHeight="200" d:DesignWidth="650">
<Grid Margin="20">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Orientation="Vertical" Grid.Row="1" Grid.Column="1" >
<TextBlock x:Name="ProgressMessage" Text="This is a test message"
HorizontalAlignment="Center" Margin="0 0 0 10" Style="{StaticResource ProgressMessage}"/>
<ProgressBar x:Name="StagingProgress" Height="25" Width="600" Value="{Binding Path=CurrentProgress}"/>
</StackPanel>
</Grid>
</UserControl>
还有 ProgressDialogViewModel:
namespace StagingWpfUI.ViewModels
{
public class ProgressDialogViewModel : Screen
{
private int _currentProgress;
private string _progressMessage;
public int CurrentProgress
{
get => _currentProgress;
set
{
_currentProgress = value;
NotifyOfPropertyChange(() => CurrentProgress);
}
}
public string ProgressMessage
{
get => _progressMessage;
set
{
_progressMessage = value;
NotifyOfPropertyChange(() => ProgressMessage);
}
}
}
}
在 ConfigureServer 方法中,我这样调用 ConfigureServerEvent:
await _events.PublishOnUIThreadAsync(new ConfigureServerEvent());
然后进入一个单独的私有方法,配置:
private void Configure(StagingModel model)
{
string csvPath = Path.Combine(_scriptPath, _sitesCsv);
string outputFile = Path.Combine(_scriptPath, "staging.csv");
_fileHelper.DeleteMarkerFile("first", "first.done");
SiteModel siteModel = _textHelper.GetSiteModelByID(model.SiteId, csvPath);
siteModel.StagingTech = model.StagingTech;
//GetStagingFiles(siteModel.SiteID);
if (model.HDReplacement == 0)
{
_logger.Info("Full server replacement selected...");
FullServerReplacement(siteModel);
}
else
{
_logger.Info("Hard drive replacement selected...");
if (model.HDLetter.ToLower() == "c:")
{
_logger.Info("C: drive replacement selected...");
CDriveReplacement(siteModel);
}
else
{
_logger.Info("D: drive replacement selected...");
DDriveReplacement(siteModel);
}
}
_logger.Info($"Writing site info for site { siteModel.SiteID } to CSV file...");
List<SiteModel> siteList = new List<SiteModel> { siteModel };
_textHelper.WriteToCsv(siteList, outputFile, false);
}
方法最终实现Progress,ProgressChanged事件被称为FullServerReplacement:
private void FullServerReplacement(SiteModel model)
{
Progress<ProgressReportModel> progress = new Progress<ProgressReportModel>();
progress.ProgressChanged += Progress_ProgressChanged;
StageMachine(model, progress);
}
最后,在 StageMachine 方法中,我正在“尝试”报告进度:
private void StageMachine(SiteModel site, IProgress<ProgressReportModel> progress)
{
ProgressReportModel report = new ProgressReportModel();
_logger.Info("***************************Stage Machine selected.***************************");
report.ProgressMessage = "Beginning staging...";
report.CurrentProgress = 0;
progress.Report(report);
// Do more work and report the progress
但是,无论我尝试了什么,我都无法让对话框更新。如有任何帮助,我们将不胜感激。
谢谢
【问题讨论】:
-
基本上你需要了解:WPF 有一个 UI 线程,它根据请求队列更新元素。牢记这一点,在视图模型之间创建更新并不难(最简单和最简单的方法是让管理器/服务跟踪应用程序并交换/实现消息传递系统)。根据提供的代码,您正在使用一些库,所以如果他们已经实现了消息传递系统,我建议您查看文档,以便不同的视图模型可以交换信息
-
能否提供您问题的最小回购协议?你的例子在哪里调用
FullServerReplacement?显示对话窗口时你在做什么? -
@mm8:我用
Configure方法的代码编辑了问题,然后调用FullServerReplacement。至于显示对话框时正在做什么:更改计算机名称,设置时区,设置环境变量,修改INI和XML,安装和卸载程序等。 -
你是在后台线程上做的吗?
-
@mm8:不。我很确定我需要这样做,尽管我无法弄清楚如何将当前线程传递给后台线程。
标签: c# wpf mvvm caliburn.micro