Trouble with Binding Can get but can't set

amirvenusamirvenus USMember ✭✭✭

Hi guys,

I am new to XF and just trying to learn Binding a bit.

In my XAML, I have the following label:

<Label HorizontalOptions="Center" VerticalOptions="Center" Grid.Column="0" Grid.ColumnSpan="3" Text="{Binding Credit}" />

and in the code behind, I have the following:

              private string credit { get; set; } 
              public string Credit  {
                        get
                        {
                            return credit; 

                        }
                        set
                        {
                            credit = value;
                    }
                             }

So when I set an initial value, for example, credit = "0.00" it works perfectly fine but my problem is setting it:

   private void Button_OnClicked(object sender, EventArgs e)
        {
        var crdString = Credit;

            float crd = float.Parse(crdString);
            crd++;
            credit = crd.ToString();
        }

But it does not update the UI.

P.S I have also set the BindingContext :

        InitializeComponent ();
            BindingContext = this;

Best Answer

Answers

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭
    Accepted Answer

    INotifyPropertyChanged?

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    Welcome to the world of binding.
    Let me suggest that doing your logic and binding to the code behind of the UI is a bad practice. It might make learning easier at first - but its a bad habit you have to unlearn.
    UI and code/logic/data should always be separate and not tightly bound.
    Hopefully this tutorial can help. Shouldn't take more than an hour.
    https://redpillxamarin.com/2016/12/14/red-pill-xamarin-introduction-to-this-series/

  • amirvenusamirvenus USMember ✭✭✭

    Thank you guys!

    I was a bit stubborn trying to force the BindingContext to be equal to this.

    But, I realised it should implement INotifyPropertyChanged and I needed to fit in
    public event PropertyChangedEventHandler PropertyChanged;

    and as an example field:

    private string _status = string.Empty;
            public string Status
            {
                get { return _status; }
                set
                {
                    if (_status != value)
                    {
                        _status = value;
    
                        if (PropertyChanged != null)
                        {
                            PropertyChanged(this, new PropertyChangedEventArgs("Status"));
                        }
                    }
                }
            }
    

    I hope it helps others! Now I need to learn about different Binding modes such as TwoWay.

    Thank you guys

Sign In or Register to comment.