保存所选项目并在另一个页面中使用它

问题描述

我正在 Xamarin.Forms 中开发移动应用。我在此页面中有“visitedDoctor”页面和列表视图。我想在主页上看选定的医生,但我无法将选定的项目转移到主页上。我应该用什么来做到这一点?

解决方法

使用 MessagingCenter 类在页面之间发送对象:

要发送消息,请使用 MessagingCenter.Send 方法 - 订阅 - 使用 MessagingCenter.Subscribe 方法:

以下是在两个页面之间发送字符串的示例:

MessagingCenter.Send<MainPage,string> (this,"Hi","John");

现在 MainPage 需要订阅:

MessagingCenter.Subscribe<MainPage,(sender,arg) => {
    // do whatever
});

您可以随意修改此代码。

,

如果你想在两个页面之间传递数据,你也可以通过构造函数来实现,我做了一个关于将ListView的selecteditem传递到另一个页面的示例。

访问医生.xaml:

<ContentPage.Content>
    <StackLayout>
        <ListView ItemsSource="{Binding doctors}" SelectedItem="{Binding selecteditem}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <Label Text="{Binding name}" />
                            <Label Text="{Binding address}" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

        <Button
            x:Name="btn1"
            Clicked="btn1_Clicked"
            Text="go to mainpage" />
    </StackLayout>
</ContentPage.Content>

要获取 selecteditem,不要忘记实现 INotifyPropertyChanged 接口以通知数据更改。

 public partial class visitedDoctor : ContentPage,INotifyPropertyChanged
{
    public ObservableCollection<doctor> doctors { get; set; }
    private doctor _selecteditem;
    public doctor selecteditem
    {
        get { return _selecteditem; }
        set
        {
            _selecteditem = value;
            RaisePropertyChanged("selecteditem");
        }
    }
    public visitedDoctor()
    {
        InitializeComponent();
        doctors = new ObservableCollection<doctor>()
        {
            new doctor(){name="doctor 1",address="address 1"},new doctor(){name="doctor 2",address="address 2"},new doctor(){name="doctor 3",address="address 3"},new doctor(){name="doctor 4",address="address 4"}

        };
        selecteditem = doctors[0];
        this.BindingContext = this;
    }

   
    public event PropertyChangedEventHandler PropertyChanged;

    
    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this,new PropertyChangedEventArgs(propertyName));
        }
    }

    private async void btn1_Clicked(object sender,EventArgs e)
    {
       await Navigation.PushAsync(new MainPage(selecteditem));
    }
}
public class doctor
{
    public string name { get; set; }
    public string address { get; set; }
}

主页:

public partial class MainPage : ContentPage
{
    public MainPage(doctor d)
    {
        InitializeComponent();

        Console.WriteLine("the selected doctor is {0}",d.name);
    }
}