从radiobutton异步更改显示的列表

时间:2016-06-05 19:40:24

标签: c# wpf asynchronous

我有一个WPF应用程序,其属性DisplayListType绑定到RadioButton。选择单选按钮将通过调用异步的MakePatientList()来更改显示的列表。当MakePatientList()完成时,它会更新显示的DxList列表,但我认为没有理由在ListTypes属性中等待它。但是确实需要调用来设置DxList属性,如下所示。 (注意:如果我不放,Visual Studio会抱怨 等待在属性setter中启动MakePatientList()。

ListTypes中的等待显然是错误的。怎么办呢?

TIA (Visual Studio 2015,.NET 4.6.1)

 private ListTypes displayListType;
        public  ListTypes DisplayListType
        {
            get { return displayListType; }
            set
            {
                displayListType = value;
                OnPropertyChanged("DisplayListType");

                switch (value)
                {
                    case ListTypes.ActiveDiagnosis:
                        await MakePatientList();  <---WRONG??
                        break;
                    .......
                }
            }
        }

private async Task MakePatientList()
        {
            // consume the WCF service.
            var result = await MedicalClient.GetActiveDxAsync(Encounter.PatientRecid, (DateTime)Encounter.Tencounter);

            dxlist = result.Select(r =>
                                new ViewDx
                                {
                                    Cdesc = r.Cdesc,
                                    Code = r.Code,
                                    Chronic = r.Chronic
                                })
                            .ToList();

            DxList = new ObservableCollection<ViewDx>(dxlist);
        }

private ObservableCollection<ViewDx> dxList;
        public ObservableCollection<ViewDx> DxList
        {
            get { return dxList; }

            set
            {
                if (dxList != value)
                {
                    dxList = value;
                    OnPropertyChanged("DxList");
                }
            }
        }

1 个答案:

答案 0 :(得分:2)

我写了一篇可能有帮助的article on async data-binding in MVVM

特别是,DxList应该是一个“异步”数据绑定属性。使用更新的NotifyTask type,它看起来像这样:

NotifyTask<ObservableCollection<ViewDx>> DxList { get; set { with notify } }

并更新如下:

private async Task<ObservableCollection<ViewDx>> MakePatientListAsync()
{
  var result = await MedicalClient.GetActiveDxAsync(Encounter.PatientRecid, (DateTime)Encounter.Tencounter);

  dxlist = result.Select(r =>
      new ViewDx
      {
        Cdesc = r.Cdesc,
        Code = r.Code,
        Chronic = r.Chronic
      })
      .ToList();

  return new ObservableCollection<ViewDx>(dxlist);
}

public  ListTypes DisplayListType
{
  get { return displayListType; }
  set
  {
    displayListType = value;
    OnPropertyChanged("DisplayListType");

    switch (value)
    {
      case ListTypes.ActiveDiagnosis:
        DxList = NotifyTask.Create(() => MakePatientListAsync());
        break;
      .......
    }
  }
}

请注意,DxList.Result现在包含可观察集合(因此您需要更新列表框绑定)。还有其他属性挂起DxList,例如DxList.IsNotCompleted,您可以将数据绑定到启用/禁用控件和/或显示/隐藏加载微调器。