Xamarin.Forms中XAML到属性的绑定

11

我对XAML中的绑定非常新手,有时真的不理解。

我的XAML代码如下:

<ActivityIndicator IsRunning="{Binding IsLoading}" IsVisible="{Binding IsLoading}" />

"IsLoading"这个绑定属性应该在哪里声明/设置?

我的.cs文件看起来像这样:

....
    public bool IsLoading;

    public CardsListXaml ()
    {
        InitializeComponent ();
        IsLoading = true;
 ....
1个回答

14

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

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

public CardsListXaml()
{
    InitializeComponent();
    BindingContext = this;
    IsLoading = true;
}

然而,仅此还不够。您当前的解决方案未实现任何属性更改通知机制,因此视图必须实现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));
        }
    }
} 

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

public CardsListView()
{
    InitializeComponent();
    BindingContext = new CardsListViewModel();
}

为了澄清,DataContext会沿着可视树往下传递,因此ActivityIndicator控件将能够读取绑定中指定的属性。

编辑:Xamarin.Forms(以及Silverlight/WPF等等...抱歉,已经有一段时间了!)还提供了一个SetBinding方法(请参见数据绑定部分)。


3
Xamarin.Forms中的BindableObject没有DataContext属性,而是有一个BindingContext属性。 - Stephane Delcroix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接