Xamarin使用QueryProperty传递值

yrdbyhpb  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(180)

我是Xamarin的初学者,我试图使用QueryProperty将值从一个页面传递到另一个页面,但是我总是得到空值。
以下是值的来源页面:

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

后面的代码:

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}");
}

下面是接收页面:

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

后面的代码:

[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");
    }
}

传递的值应该放在标签和弹出窗口显示警报中。当我试图放置断点时,str值仍然为空。在页面之间导航是好的。
有人能指出错误在哪里吗T_T提前谢谢。

ntjbwcob

ntjbwcob1#

您的属性“str”需要引发PropertyChanged事件,以便绑定更新值:

[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");
    }
}

但是,由于参数只在Page3构建完成后设置,所以showdisp()方法不会有正确的值,需要稍后调用。
您还应该考虑使用ViewModel并应用MVVM。

相关问题