Home > Enterprise >  Xamarin passing values using QueryProperty
Xamarin passing values using QueryProperty

Time:10-02

I am a beginner at Xamarin and I am trying to pass value from one page to another using QueryProperty, but I keep getting null values.

Here is the Page where the value comes from:

<StackLayout>
    <Button Text="Pass" Command="{Binding passCommand}"></Button>
</StackLayout>

The code behind:

public Page()
{
    InitializeComponent();
    passCommand = new Command(passFunc);
    BindingContext = this;
}

public ICommand passCommand { get; }
private async void passFunc()
{
    string str = "Hello";
    await Shell.Current.GoToAsync($"{nameof(Page3)}?str={str}");
}

And here is the receiving page:

<StackLayout>
    <Label Text="{Binding str}"/>
</StackLayout>

The code behind:

[QueryProperty(nameof(str), nameof(str))]
public partial class Page3 : ContentPage
{
    public Page3()
    {
        InitializeComponent();
        BindingContext = this;
        showdisp();
    }
    public string str { set; get; }
    public async void showdisp()
    {
       await App.Current.MainPage.DisplayAlert("Hello", str, "OK");
    }
}

The passed value should be put in the Label and the popup display alert. When I tried to put breakpoints, str value is still null. Navigating between pages are fine.

Can someone point out if where the error is T_T Thanks in advance.

CodePudding user response:

Your property "str" needs to raise a PropertyChanged event, so that the binding updates the value:

[QueryProperty(nameof(str), nameof(str))]
public partial class Page3 : ContentPage
{
    public Page3()
    {
        InitializeComponent();
        BindingContext = this;

        // attention: this won't show the passed value,
        // because QueryProperty values only are set after construction 
        //showdisp();
    }

    private string _str;
    public string str
    {
        get => _str;
        set 
        {
            if(_str == value) return;

            _str = value;

            // Let the bound views know that something changed, so that they get updated 
            OnPropertyChanged();

            // optional, call showdisp() when value changed
            showdisp();
        }
    }

    public async void showdisp()
    {
       await App.Current.MainPage.DisplayAlert("Hello", str, "OK");
    }
}

However, since the parameter only is set after construction of Page3 finished, your showdisp() method won't have the correct value. You need to call it later.

You should also consider using a ViewModel and apply MVVM.

  • Related