Xamarin表格中的触发活动指标

Geo*_*rds 5 c# xaml xamarin

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

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

<Button x:Name="NewDeviceButton" 
          Image="glyphish_31_circle_x.png" 
          HorizontalOptions="End"
          VerticalOptions="EndAndExpand" />
Run Code Online (Sandbox Code Playgroud)

单击它时,我想在一段时间内显示它,然后触发一些C#功能:

<ActivityIndicator Color="Black" IsRunning="true" />
Run Code Online (Sandbox Code Playgroud)

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

Jam*_*gno 6

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

您可以简单地为每个人提供一个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
}
Run Code Online (Sandbox Code Playgroud)

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

<ActivityIndicator IsRunning="{Binding IsBusy}"
                       Color="Blue"/>
Run Code Online (Sandbox Code Playgroud)

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


Seb*_*ste 5

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

  1. 我很懒,INotifyPropertyChanged如果我不需要,我不想设置实现
  2. 默认情况下, XF应该使用该属性来显示通知。这似乎不起作用,但如果它确实起作用,这种方法已经让我们能够利用它

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

IE:

主页.xaml:

<ContentPage ... x:Name="myPage">
    ...
    <ActivityIndicator IsVisible="{Binding Source={x:Reference myPage}, Path=IsBusy}" IsRunning="{Binding Source={x:Reference myPage}, Path=IsBusy}" />
    ...
</ContentPage>
Run Code Online (Sandbox Code Playgroud)

MainPage.xaml.cs:

...
async void OnDoSomethingLong(...)
{
    if (!this.IsBusy)
    {
        try
        {
            this.IsBusy = true;

            //await long operation here, i.e.:
            await Task.Run(() => {/*your long code*/});
        }
        finally
        {
            this.IsBusy = false;
        }
    }
}
...
Run Code Online (Sandbox Code Playgroud)