Search code examples
.netxamlmaui

How to pass variable to children in .net maui?


im trying to create some kind of reusable message component that displays info/warning/err/ok message.

So in my content page its like

<views:MessageView />

but i need to pass props to this view from parent

like text of the message & type so developer can choose which one wants to display

also i would like to use MVVM but if that's problem i can use codebehind

i imagine something like this ?

<views:MessageView MessageText={Binding ErrMsg} MessageType={Binding Type} />

is it possible in .net maui ?


Solution

  • No problem. First of all. Don't use BindingContext in your control. The control is dependent of the view it is currently attached to.

    To communicate with your control you can read about bindable-properties

    So in your control it can look like this.

    public static readonly BindableProperty MessageTextProperty =
        BindableProperty.Create(nameof(MessageText), typeof(string), typeof(MyControl));
    
    public string MessageText
    {
        get => (string)GetValue(MessageTextProperty);
        set => SetValue(MessageTextProperty, value);
    }
    

    So when you bind to your ViewModel, it will fetch data and send it to your control.

    Update

    Here is complete code that is a common way to update a label.

    public partial class MessageView : ContentView
    {
        public static readonly BindableProperty MessageTextProperty =
                BindableProperty.Create(nameof(MessageText), typeof(string), typeof(MessageView), defaultValue: default(string), propertyChanged: OnTextChanged);
    
        private static void OnTextChanged(BindableObject bindable, object oldValue, object newValue)
        {
            var messageView = (MessageView)bindable;
            messageView.MyLabel.Text = (string)newValue;
        }
    
        public string MessageText
        {
            get => (string)GetValue(MessageTextProperty);
            set => SetValue(MessageTextProperty, value);
        }
    
        public MessageView()
        {
            InitializeComponent();
        }
    }
    

    In your view you use the control like this:

    <controls:MessageView MessageText="{Binding MyMessage}" />
    

    With the Binding in the ViewModel

    [ObservableProperty]
    private string myMessage = "Hello everybody!";