Search code examples
xamarindata-bindingxamarin.forms

Binding string with Button


I am trying to bind a string to a Button in pure C# (no XAML), but apparently I am doing it wrong, as the result of my code is that the button disappears.

I am defining my property as follows:

public string selectionString { get; set; }

And this is how I am binding the string to the button:

        selectionString = "Hello";
        selectionButton = new Button
        {
            TextColor = Color.Black
        };
        selectionButton.SetBinding(Button.TextProperty, "selectionString");
        Children.Add(selectionButton); 

I have tried to use BindingMode.TwoWay, but it doesn't work.

Of course, setting the text and removing the binding makes the button appear and work.

My need is just this: the button text should be the selectionString, and if this changes by an external event, so the button's text should change accordingly.

Am I missing something in how the binding works?


Solution

  • Bindings work against public properties on the view's binding context, and respond to INotifyPropertyChanged events firing. Hopefully this demonstrates for you.

    public class MyViewModel : INotifyPropertyChanged
    {
      // Fire RaisePropertyChanged in the setter, I use Fody to weave this in
      public string SelectionString {get;set;}
    }
    
    public class MyView : Page
    {
      protected override void OnBindingContextChanged()
      {
        if (BindingContext is MyViewModel)
        {
          this.SetBinding(Button.TextProperty, "SelectionString");
        }
      }
    }