c# - 在两个内容页面之间传递数据;

标签 c# xamarin.android visual-studio-mac .net-maui

我对毛伊岛的编程相当陌生。之前,我在 Xamarin 中编写了 Android 应用程序。我有问题。如何在两个内容页面之间传输变量。我尝试这样:

我有两个内容页面,MainPage 和 SettingsPage。这是我将数据发送到 SettingsPage 的方式:

public async void goToSettingsPage_button_Clicked(object sender, EventArgs e)
{
  await Navigation.PushAsync(new DetailsPage(language));
}

这就是我对它们的看法:

public partial class SettingsPage : ContentPage
{
public SettingsPage(string language)
{
    InitializeComponent();
   
    String Language = language;
}
}

我刚刚在 xamarin 上使用了 Intent。 PutExtra 或 Intent.GetExtra。我不知道如何在毛伊岛工作。如何将变量从 SettingsPage 传递回 MainPage。我尝试按照上面的方法做;

最佳答案

您可以使用MessagingCenter将数据发送到其他页面。另外,您也可以用同样的方式将数据发送回来。

首先,您可以在MyWordPage.Xalm.cs的 View 模型中向订阅者发送消息,如下所示:

private void Button_Clicked(object sender, EventArgs e)
{
      MessagingCenter.Send<MainPage, String>(this, "language", English);
}

其次,在MainPage的 View 模型中,您可以订阅消息,代码如下:

public class MainPageViewModel: INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        public String mylanguage = "asd" ;
        public String Mylanguage {
            get
            {
                return mylanguage;
            }
            set
            {
                if(mylanguage != value)
                {
                    mylanguage = value;          
                    OnPropertyChanged(nameof(Mylanguage));
                }
            }
        }
        public MainPageViewModel()
        {
            MessagingCenter.Subscribe<MainPage, Sring>(this, "language", (sender, arg) =>
            {
                Mylanguage = arg;
            });
        }
    }

最后,我们可以将mylanguage绑定(bind)到MainPage.xaml中的标签:

<Label Text="{Binding mylanguage} "  ></Label>

更多信息您可以引用Publish and subscribe to messages .

关于c# - 在两个内容页面之间传递数据;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74208154/

相关文章:

android - 自定义标签 "Specified child already has a parent"

c# - 在 MvvmCross 中使用 MvxGridView

visual-studio-mac - Visual Studio for Mac 2022 - 热重载?

c# - Visual Studio : how to use scripts to "build solution" ,"rebuild solution", 或脚本而不是单击 "start"按钮

c# - Winforms绑定(bind)问题

c# - 如何在子组上使用 GroupBy

c# - 应用程序级别变量

mono - CSC : error CS0041: Unexpected error writing debug information -- 'Operation is not supported on this platform.'

asp.net - 如何在 Visual Studio For Mac 中将 Web API 发布到部署槽?

c# - 简单注入(inject)器 : Different DbContext for selected controllers