命令调用之前的UI控件可见性?

时间:2015-05-22 09:29:10

标签: c# wpf mvvm mahapps.metro

我有一个按钮命令,它发送几封电子邮件,因此需要几秒钟才能执行该方法。我想要显示进度响铃Mahapps.Metro&在此方法执行时禁用视图。

以下是我的观点中的ProgressRing

 <Controls:ProgressRing IsActive="True" Visibility="{Binding IsProgressRingVisible, UpdateSourceTrigger=PropertyChanged}" />

ViewModel财产:

  private Visibility _IsProgressRingVisible;
  public Visibility IsProgressRingVisible
   {
     get { return _IsProgressRingVisible; }
     set
      {
        _IsProgressRingVisible = value;
        OnPropertyChanged("IsProgressRingVisible");
      }
    }   

&安培;最后我的按钮命令逻辑:

 private void DisableView()
        {
            IsProgressRingVisible = Visibility.Visible;
            IsEditable = false;
        }

  private void ApprovePublicationCommandAction()
        {
            DisableView();

            try
            {              
                Send emails blah bah

显然,命令方法逻辑在通知UI之前运行。更改ProgressRing可见性。有没有办法可以显示ProgressRing然后继续执行命令逻辑?

2 个答案:

答案 0 :(得分:2)

您可以创建类似CommandIsExecuting的属性,并且可以将此属性绑定到whenExecuting该命令的Action。

以下是AsyncRelayCommand ctor

的代码段
readonly Func<T, Task> _asyncExecute;
        readonly Predicate<T> _canExecute;
        readonly Action<bool> _whenExecuting;
public AsyncRelayCommand(Func<T, Task> asyncExecute, Predicate<T> canExecute, Action<bool> whenExecuting)
        {
            if (asyncExecute == null)
                throw new ArgumentNullException("asyncExecute");

            _asyncExecute = asyncExecute;
            _canExecute = canExecute;
            _whenExecuting = whenExecuting;
        }

然后在您实现命令的ViewModel中,只需将whenExecuting用于本地属性,如下所示

    private bool _commandIsExecuting;
    public virtual bool CommandIsExecuting
    {
        get
        { return _commandIsExecuting; }
        protected set
        {
            _commandIsExecuting = value;
            OnPropertyChanged(() => this.CommandIsExecuting);
        }
    }

MyCommand = new AsyncRelayCommand<object>(CommandImplementation, CanIExecute, (b) => CommandIsExecuting = b);

答案 1 :(得分:0)

结束制作我的方法Async

private async void ApprovePublicationCommandAction()
{
   DisableView();

   await Task.Factory.StartNew(() =>
    {
      try
       {
         Send emails blah blah

然后在工作完成后启用视图,不会抛出异常。谢谢你的帮助。