Emixam23
Emixam23

Reputation: 3964

Xamarin Forms - Label, Color and other attribute doesn't update when their Binded attributes are set

I'm comming because I don't understand something about the binding..

I have this attribute in the C# code:

public string MyText { get; set; }

and then in the XAML part:

<Label Text="{Binding MyText}"/>

The first time it works, but if I change MyText string, then the <Label/> doesn't update..

I also saw some post about it, where people speak about INotifyChange or something like that, how does work this Bind? Why the update isn't constant and why it just not work same always?

The problem is that my projet is a bit complex. I have a customCalendar I made by myself which is a Grid "bind by myself again" to a DayCase[6][7] such as Windows calendar, the display is the same.

So my question is double, does I need 1 function by attribute to "listen" if one of them change? Because in the example, I just speak about one Label, but I have 1 label by DayCase, 3 Color to update, a title with Month/Year to update, etc etc

I really lost honestly, I'm sure to know how to think, how to make it..

Thank for your help!

Upvotes: 1

Views: 698

Answers (1)

Bonelol
Bonelol

Reputation: 546

To make binding work. Your ViewModel needs to implement INotifyPropertyChanged, it has an handler public event PropertyChangedEventHandler PropertyChanged, which Xamarin.Forms' binding system to hook up with, and create an invoker for it:

protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            var eventHandler = PropertyChanged;
            eventHandler?.Invoke(this, e);
        }

After that, write your property that to be bind like this:

private string _myText;
    public string MyText
    {
        get { return _myText; }
        set
        {
            if (_myText != value)
            {
                _myText = value;
                OnPropertyChanged(new PropertyChangedEventArgs(nameof(MyText)));
            }
        }
    }

For details, please read https://developer.xamarin.com/guides/xamarin-forms/xaml/xaml-basics/data_bindings_to_mvvm/

Also, there are other MVVM frameworks (MvvmCross, Mvvm Light, etc.) or Xamarin.Forms.Lab already did some work for you.

For your customCalendar issue, since to let binding work is to invoke PropertyChanged event, you can write a method to handle this like

public void UpdateDayCase(int i, int j, DayCase)
{
    this.DayCases[i][j] = DayCase;
    OnPropertyChanged(new PropertyChangedEventArgs(nameof(DayCases)));
}

Upvotes: 1

Related Questions