I am a total newbie with bindings in xaml and I really don\'t get it sometimes.
I have this in my xaml:
Bindings are typically resolved from the BindingContext
property (in other implementations, this property is called DataContext
). This is null
by default (at least in other implementations of XAML), thus your view is unable to find the specified properties.
In your case, you must set the BindingContext
property to this
:
public CardsListXaml()
{
InitializeComponent();
BindingContext = this;
IsLoading = true;
}
However, this alone will not suffice. Your current solution does not implement a mechanism to notify the view of any property changes, so your view would have to implement INotifyPropertyChanged
. Instead, I suggest you implement the Model-View-ViewModel pattern, which not only fits beautifully with data binding, but will result in a more maintainable and testable code base:
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));
}
}
}
And then in your code-behind's constructor:
public CardsListView()
{
InitializeComponent();
BindingContext = new CardsListViewModel();
}
Just to clarify, DataContext
cascades down the visual tree, thus the ActivityIndicator
control will be able to read to properties specified in the bindings.
Edit: Xamarin.Forms (and Silverlight/WPF etc... sorry, it's been a while!) also provides a SetBinding method (see the Data Binding section).