xamarin.forms从xaml绑定到property

我是一个在xaml中绑定的新手,我有时候真的不明白。

我在我的xaml中有这个:

 

绑定“IsLoading”。 我在哪里声明/设置这个属性?!

我的.cs看起来像这样:

 .... public bool IsLoading; public CardsListXaml () { InitializeComponent (); IsLoading = true; .... 

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

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

 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方法(参见数据绑定部分)。