首页 > 解决方案 > 如何在 Xamarin.Forms MVVM 中使用 MessagingCenter 动态添加按钮

问题描述

我想在动态视图中添加按钮,例如在某些情况下我会添加 2 个按钮,在某些情况下我会添加 4 个按钮,但我想在一个视图中概括所有这些逻辑,我只向其中传递参数(例如视图)标题,按钮数量等...以便用户按以下方式部署...

2 个按钮 4 个按钮

为此,请丢弃某些实现:

1.- 使用 a ,因为如果列表中的元素很少,这会产生一个死区 2.- 使用控件,因为这对于 Android-iOS 不存在

当使用 MVVM 作为架构模式时,我很难将参数传递给 CodeBehind,因为之前使用了一个 MessagingCenter,我在其中传递了一个字符串列表,我最终通过它并添加了按钮,但这不起作用

您有以下带有相应 x 的视图:名称...

查看.xaml:

<Label
         Text="{Binding Titulo}"
         HorizontalOptions="CenterAndExpand">
</Label>

<StackLayout 
          x:Name="EntriesStackLayout">

</StackLayout>

在 View 的 ViewModel 中,我通过 MessagingCenter 传递列表

ViewModel.cs:

#region Constructor
public OptionsPopUpViewModel(string title, List<string> opciones)
{         
    Titulo = title;
    opcionesMensaje = opciones;

    MessagingCenter.Send((App)Xamarin.Forms.Application.Current, "Opciones", opcionesMensaje);
}
#endregion

然后在视图后面的代码中,我在 OnAppearing () 方法中收到并在视图中创建按钮

查看.xaml.cs:

 public OptionsPopUpView()
 {
     InitializeComponent();
 }

  protected override void OnAppearing()
  {
      base.OnAppearing();

      MessagingCenter.Subscribe<App, List<string>>((App)Xamarin.Forms.Application.Current, "Opciones", (s, opcionesMensaje) =>
      {
          foreach (var item in opcionesMensaje)
          {
              Button boton = new Button();

               EntriesStackLayout.Children.Add(boton);
          }

      });
 }

 protected override void OnDisappearing()
 {
      base.OnDisappearing();
      MessagingCenter.Unsubscribe<App, List<string>>(this, "Opciones");
 }

预期行为:根据列表中的项目数添加按钮

获得的行为:跟踪代码时,第一个没有执行OnAppering()方法,我第二次运行时进入方法并正确执行,但是没有添加按钮

为什么我会出现这种行为?因为如果我在 MessagingCenter 中收到列表,我的代码无法添加按钮?

消息中心

我究竟做错了什么?对我有什么帮助吗?

我希望这个问题可以帮助那些有同样问题的人

问候!

标签: c#xamarinmvvmxamarin.formsmessaging

解决方案


推荐阅读