xamarin.forms从xaml绑定到property

ull*_*trm 11 c# xaml xamarin.forms

我是xaml中绑定的新手,我有时候真的不明白.

我在我的xaml中有这个:

<ActivityIndicator IsRunning="{Binding IsLoading}" IsVisible="{Binding IsLoading}" />
Run Code Online (Sandbox Code Playgroud)

绑定"IsLoading".我在哪里声明/设置这个属性?!

我的.cs看起来像这样:

....
    public bool IsLoading;

    public CardsListXaml ()
    {
        InitializeComponent ();
        IsLoading = true;
 ....
Run Code Online (Sandbox Code Playgroud)

Jam*_*ght 14

绑定通常从BindingContext属性中解析(在其他实现中,调用此属性DataContext).这是null默认情况下(至少在XAML的其他实现中),因此您的视图无法找到指定的属性.

在您的情况下,您必须将BindingContext属性设置为this:

public CardsListXaml()
{
    InitializeComponent();
    BindingContext = this;
    IsLoading = true;
}
Run Code Online (Sandbox Code Playgroud)

但是,仅靠这一点是不够的.您当前的解决方案没有实现一种机制来通知视图任何属性更改,因此您的视图必须实现INotifyPropertyChanged.相反,我建议你实现Model-View-ViewModel模式,它不仅非常适合数据绑定,而且会产生更易于维护和可测试的代码库:

public class CardsListViewModel : INotifyPropertyChanged
{
    private bool isLoading;
    public bool IsLoading
    {
        get
        {
            return this.isLoading;
        }

        set
        {
            this.isLoading = value;
            RaisePropertyChanged("IsLoading");
        }
    }

    public CardsListViewModel()
    {
        IsLoading = true;
    }

    //the view will register to this event when the DataContext is set
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

然后在你的代码隐藏构造函数中:

public CardsListView()
{
    InitializeComponent();
    BindingContext = new CardsListViewModel();
}
Run Code Online (Sandbox Code Playgroud)

只是为了澄清,DataContext沿着可视化树级联,因此ActivityIndicator控件将能够读取绑定中指定的属性.

编辑:Xamarin.Forms(和Silverlight/WPF等...对不起,已经有一段时间了!)还提供了一个SetBinding方法(参见数据绑定部分).

  • `Xamarin.Forms``BindableObject`s没有`DataContext`属性,但是`BindingContext` (3认同)