【问题标题】:How to have multi BindingContext in a page?如何在一个页面中有多个 BindingContext?
【发布时间】:2021-05-15 22:08:31
【问题描述】:

如何创建 2 pass 视图?在谷歌上没有找到类似的东西

我有一个 onePage.xaml.cs,它正在调用 OneViewModel。在 oneViewModel 中,它会刷新页面,它应该调用 twoViewModel。最后 twoViewModel 会调用一些随机视图

如何编辑 view.xaml.cs 文件来处理 2 个不同的 ViewsModel?第一遍应该绑定到 oneViewModel,第二遍应该绑定到 twoViewModel

onePage.xaml(视图)

<Label Text={Binding TestLabel} />

onePage.xaml.cs(视图)

    public onePage()
        {
            InitializeComponent();

           BindingContext = new oneViewModel();
    }

oneViewModel.cs(视图模型 1)

  async oneViewModel()
   {
      TestLabel = "View Mode 1"
     await Shell.Current.GoToAsync(Shell.Current.CurrentState);
   }

twoViewModel.cs(视图模型 2)

async twoViewModel()
{
    TestLabel = "View Mode 2"
    await Shell.Current.GoToAsync(RandomPage);
}

【问题讨论】:

  • 这绝对是零意义。但是如果你想改变一个页面绑定的VM,只需重新分配BindingContext
  • 已经试过了,没用。如果我将 BindingContext 重新分配给第二个视图模型,则它不会识别 TestLabel 或任何视图对象。你有可以举出更多例子的例子吗?随时发布答案

标签: c# xamarin xamarin.forms xamarin.android xamarin.ios


【解决方案1】:

只需更新页面的BindingContext

<StackLayout Padding="0,100,0,0">
    <Label Text="{Binding Description}" />
    <Button Text="Change" Clicked="Button_Clicked" />
</StackLayout>

代码隐藏

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

        this.BindingContext = new VM("one");
    }

    void Button_Clicked(System.Object sender, System.EventArgs e)
    {
        this.BindingContext = new VM("two");
    }
}

public class VM
{
    public string Description { get; set; }

    public VM(string desc)
    {
        this.Description = desc;
    }
}

【讨论】:

    猜你喜欢
    • 2015-02-09
    • 2014-05-28
    • 1970-01-01
    • 2018-09-21
    • 2021-03-26
    • 1970-01-01
    • 2015-09-29
    • 2017-10-28
    • 2020-01-26
    相关资源
    最近更新 更多