繁忙指示器未显示在异步方法中

时间:2018-01-09 09:34:55

标签: c# wpf mvvm xceed-plus-edition

我正在使用Extended WPF ToolkitMVVM Light个库。

我想实现WPF Toolkit繁忙指标,并定期通知用户一些信息(与viewmodel中的BusyMessage属性绑定)。

但是,单击“开始”按钮时,不会显示繁忙指示符(IsBusy绑定到viewmodel中的IsBusy属性)。我做错了什么? 奇怪的是,它在视图模型的构造函数中将IsBusy设置为true时有效。

的App.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;
    }
}

1 个答案:

答案 0 :(得分:3)

这正是我更喜欢ReactiveUI的原因 - 它有&#34;忙指示符&#34;内置于ReactiveCommand中,甚至是异步命令。

至于你的问题,我会说你的RaisePropertyChanged(nameof(_isBusy));错了,它应该是RaisePropertyChanged(nameof(IsBusy)); // name of the public property

此外,根据您的RaisePropertyChanged实现,您可以将参数留空并只使用RaisePropertyChanged();