Xamarin表格中的触发活动指标

我的Xamarin.Forms应用程序上有一个图标,当点击它时,我想将其更改为活动指示器。 看起来我应该使用Trigger ,事件触发器看起来不错,但是当我的图像在XAML中声明时,我不确定它是如何组合在一起的?

目前,我在stacklayout底部的XAML中有这个:

 

单击它时,我想在一段时间内显示此信息,然后触发一些C#function:

  

我不确定是否最好在XAML中使用触发器配置它,或者我是否可以在XAML中拥有占位符类型项,然后在C#中拥有所有定义?

有几种方法可以做到这一点。

您可以简单地为每个人提供一个x:Name,然后如果要隐藏它,则打开/关闭IsRunning和IsVisible。

我假设你有一些数据绑定正在进行中。 由于IsRunning是一个bool,你可以简单地将它绑定到后面的代码中的布尔值。 例如,在我的ViewModel中,我有一个IsBusy属性并实现了INotifyPropertyChanged:

 public class MyViewModel : INotifyPropertyChanged { public MyViewModel() { } private bool busy = false; public bool IsBusy { get { return busy; } set { if (busy == value) return; busy = value; OnPropertyChanged("IsBusy"); } } public async Task GetMonkeysAsync() { if (IsBusy) return; try { IsBusy = true; //do stuff here that is going to take a while } finally { IsBusy = false; } } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string name) { var changed = PropertyChanged; if (changed == null) return; changed(this, new PropertyChangedEventArgs(name)); } #endregion } 

然后在XAML中你可以绑定到IsBusy:

  

我认为应该处理它。 如果你需要一个计时器,你可以使用我在这里的相同绑定,并使用内置计时器类的Xamarin.Forms。

James的回答是正确的,但是,我更喜欢使用页面自己的IsBusy属性,原因有两个:

  1. 我很懒,如果不需要,我不想设置INotifyPropertyChanged实现
  2. XF被禁止使用该属性默认显示通知 。 这似乎不起作用,但如果它确实如此,这种方法已经让我们可以利用它

与James的回答(除了删除INPC实现之外)的唯一区别在于,您需要为页面命名( x:Name="myPage" ),然后使用{Binding Source={x:Reference myPage}, Path=IsBusy}使用对它的引用来声明绑定{Binding Source={x:Reference myPage}, Path=IsBusy}对于ActivityIndi​​cator的IsVisibleIsRunning{Binding Source={x:Reference myPage}, Path=IsBusy}

即:

MainPage.xaml中:

  ...  ...  

MainPage.xaml.cs中:

 ... async void OnDoSomethingLong(...) { if (!this.IsBusy) { try { this.IsBusy = true; //await long operation here, ie: await Task.Run(() => {/*your long code*/}); } finally { this.IsBusy = false; } } } ...