我正在使用 Extended WPF Toolkit和 MVVM Light图书馆。
我想实现 WPF 工具包繁忙指示器并定期通知用户一些信息(与 View 模型中的 BusyMessage 属性绑定(bind))。
但是,当单击“开始”按钮时,不显示忙碌指示器(IsBusy 绑定(bind)到 viewmodel 中的 IsBusy 属性)。我做错了什么?
奇怪的是,当在 View 模型的构造函数中将 IsBusy 设置为 true 时,它会起作用。
应用程序.xaml
public partial class App : Application
{
public App()
{
DispatcherHelper.Initialize();
}
}
窗口
<Window xmlns:xctk='http://schemas.xceed.com/wpf/xaml/toolkit'
DataContext='{Binding Main, Source={StaticResource Locator}}'>
<StackPanel>
<xctk:BusyIndicator IsBusy='{Binding IsBusy}'>
<xctk:BusyIndicator.BusyContentTemplate>
<DataTemplate>
<StackPanel Margin='4'>
<TextBlock Text='{Binding DataContext.BusyMessage, RelativeSource={RelativeSource AncestorType={x:Type Window}}}' />
</StackPanel>
</DataTemplate>
</xctk:BusyIndicator.BusyContentTemplate>
<Button Content='Start ...'
Command='{Binding StartCommand}'
HorizontalAlignment='Center'
VerticalAlignment='Center' />
</xctk:BusyIndicator>
查看模型
public class MainViewModel : ViewModelBase
{
private string _busyMessage;
public string BusyMessage
{
get { return _busyMessage; }
set
{
if (_busyMessage != value)
{
_busyMessage = value;
RaisePropertyChanged(nameof(_busyMessage));
}
}
}
private bool _isBusy;
public bool IsBusy
{
get { return _isBusy; }
set {
if (_isBusy != value)
{
_isBusy = value;
RaisePropertyChanged(nameof(_isBusy));
}
}
}
public RelayCommand StartCommand
{
get { return new RelayCommand(() => StartExecute()); }
}
private async void StartExecute()
{
IsBusy = true;
await Task.Run(() =>
{
//update UI from worker thread
DispatcherHelper.CheckBeginInvokeOnUI(() => BusyMessage = "Work 1 Done");
Thread.Sleep(1000);
//update UI from worker thread
DispatcherHelper.CheckBeginInvokeOnUI(() => BusyMessage = "Work 2 Done");
});
IsBusy = false;
}
public MainViewModel()
{
//Works when boolean is set to 'true' in constructor
//IsBusy = true;
}
}
最佳答案
这正是我更喜欢 ReactiveUI 的原因- 它在 ReactiveCommand 中内置了“忙碌指示器”,甚至是异步的。
至于你的问题,我想说你的RaisePropertyChanged(nameof(_isBusy));
错了,应该是RaisePropertyChanged(nameof(IsBusy)); // name of the public property
此外,根据您的 RaisePropertyChanged 实现,您可以适本地将参数留空并使用 RaisePropertyChanged();
关于c# - 异步方法中未显示忙碌指示符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48165108/