RichardS
RichardS

Reputation: 85

How can I pass a bound value from one class to another in Xamarin?

I have a class that looks like this. I would like to create an Info class inside of it and have the value of the text in Info bound to the view model (_vm.A). I know how to pass a string into the class Info, but how can I pass a bound value that will change over time.

public class InfoPage
{
    private readonly InfoViewModel _vm;

    public InfoPage() : base()
    {
        BindingContext = _vm = new InfoViewModel();
        var info = new Info(_vm.A);
    }

    public ChangeValueX() {
        _vm.A = "XXX";
    }

    public ChangeValueY() {
        _vm.A = "YYY";
    }
}

public Info(??? ???)
{
    
   var Label1 = new Label()
        .Bind(Label.TextProperty, ???, source: this);
    
}

This is just a simple example as there is much more to my code.

Can someone tell me how I can pass a bound value to class Info so when the bound value in the ViewModel changes then the text changes. As I don't know how to do it I just used question marks for now.

Note the ViewModel looks like this:

private string _a;
public string A{ get => _a; set => SetProperty(ref _a, value); }

Upvotes: 1

Views: 43

Answers (1)

Lucas Zhang
Lucas Zhang

Reputation: 18861

In your case you could use BindableProperty

in Info class

public class Info:BindableObject
    {
        public static readonly BindableProperty StringValueProperty =
BindableProperty.Create("StringValue", typeof(string), typeof(Info),string.Empty);

        public string StringValue
        {
            get { return (string)GetValue(StringValueProperty); }
            set { SetValue(StringValueProperty, value); }
        }

        public Info()
        {
            Label label = new Label();
            label.SetBinding(Label.TextProperty, new Binding("StringValue", source: this));
        }


    }

in page

 Info info = new Info();
info.SetBinding(Info.StringValueProperty, new Binding("xxx", source: this));

Upvotes: 1

Related Questions