首页 > 解决方案 > 当数据库在后台进行更新时,如何让我的 UI 响应按钮点击?

问题描述

我有按下按钮时调用的这段代码:

async void OnTapped(object sender, System.EventArgs e)
{
    var btn = sender as ButtonTemplate;
    if (btn == null)
        return;
    if (btn.Text == Settings.cc.ShortText())
        return;
    if (Counts.phaseTableSelectedCardCount != 0)
    {
        var canContinue = await this.DisplayAlert("Selector", "Changing this will remove all previously selected cards from the deck", "OK", "Cancel");
        if (canContinue == false)
            return;
    }
    var settingId = SetButtons(btn.Text);
    //
    // These updates take 1-3 seconds
    //
    App.DB.UpdateSelected(false);
    App.DB.UpdateIntSetting(SET.Cc, settingId);
    AddDetailSection();
}

public void AddDetailSection()
{
    vm.IsBusy = true;
    Change.cardSelection = true;
    App.DB.GetData();
    detailsLayout.Children.Clear();   
    detailsLayout.Children.Add(CreateDetailSection(null));
    SetPageDetails();
    vm.IsBusy = false;
}

按下按钮后,SetButtons(btn.Text);代码会更改按钮颜色。但是,直到 2-3 秒后,当这些行执行后,我才看到对 UI 的影响,     

App.DB.UpdateSelected(false);
App.DB.UpdateIntSetting(SET.Cc, settingId);
AddDetailSection();

有没有办法可以改变 UI 颜色并且上面三行可以在后台运行?

标签: c#xamarinxamarin.forms

解决方案


尝试类似这里的东西

  async void OnTapped(object sender, System.EventArgs e)
  {
     var btn = sender as ButtonTemplate;
     if (btn == null)
        return;
     if (btn.Text == Settings.cc.ShortText())
        return;
     if (Counts.phaseTableSelectedCardCount != 0)
     {
        var canContinue = await this.DisplayAlert("Selector", "Changing this will remove all previously selected cards from the deck", "OK", "Cancel");
        if (canContinue == false)
           return;
     }
     var settingId = SetButtons(btn.Text);
     await Task.Run(() => AddDetailSection(settingId));
  }

  public void AddDetailSection(int settingId)
  {
     App.DB.UpdateSelected(false);
     App.DB.UpdateIntSetting(SET.Cc, settingId);
     AddDetailSection();
     vm.IsBusy = true;
     Change.cardSelection = true;
     App.DB.GetData();
     detailsLayout.Children.Clear();
     detailsLayout.Children.Add(CreateDetailSection(null));
     SetPageDetails();
     vm.IsBusy = false;
  }

推荐阅读