【问题标题】:Pass an argument from viewmodel to a page's ctor via TabBar Xaml?通过 TabBar Xaml 将视图模型中的参数传递给页面的 ctor?
【发布时间】:2020-10-19 15:31:14
【问题描述】:

我正在使用 Xamarin Form 的 Shell 在页面底部创建三个选项卡。其中一个页面正在接受一个假设来自 MainViewModel 的参数(之前的设计是页面的图标位于主屏幕中,我将 PushAsync 并通过 ctor 传递参数,很简单)。但由于我重新设计了应用程序以使用 Shell 和 Tab,我不知道如何通过 xaml 从 MainViewModel 传递页面的 ctor 参数。

任何帮助将不胜感激,谢谢。

<!--<ShellItem>
    <ShellContent>
        <pages:MainView/>
    </ShellContent>
</ShellItem>-->

<TabBar>
    <Tab Title="Main" Icon="mainscreen.png">
        <ShellContent>
            <pages:MainView/>
        </ShellContent>
    </Tab>

    <Tab Title="News" Icon="googlenews.png">
        <ShellContent>
            <pages:NewsView/>
        </ShellContent>
    </Tab>

    <Tab Title="Search" Icon="search.png">
        <ShellContent>
            <pages:SearchView> // need to pass this page an argument from MainViewModel
                <x:Arguments>
                    <vm:MainViewModel ListViewItems=""></vm:MainViewModel>
                </x:Arguments>
            </pages:SearchView>
        </ShellContent>
    </Tab>
</TabBar>
 public partial class SearchView : ContentPage
{
    public SearchView(ObservableCollection<DailyIRD> dailyIrd)
    {
        InitializeComponent();

        BindingContext = new SearchViewModel(this, dailyIrd);
    }
}

【问题讨论】:

    标签: xamarin xamarin.forms


    【解决方案1】:

    我创建了一个带有Title 属性的MainViewModel 进行测试。下面的方法效果很好。

    MainViewModel.cs

     public class MainViewModel  
    {
        public string Title { get; set; } = string.Empty;
        public MainViewModel()
        {
            Title = "MainViewModel";
        }
    }
    

    AppShell.xaml:

        <Tab Title="Search" Icon="monkeyicon.png">
            <ShellContent>
                <local:SearchView>
                    <local:SearchView.BindingContext>
                        <vm:MainViewModel />
                    </local:SearchView.BindingContext>
                    <!--  // need to pass this page an argument from MainViewModel  -->
                    <!--<x:Arguments>
                        <vm:MainViewModel Title="{Binding .}" />
                    </x:Arguments>-->
                </local:SearchView>
            </ShellContent>
        </Tab>
    

    SearchView.xaml:

     <ContentPage.Content>
        <StackLayout>
            <Label
                HorizontalOptions="CenterAndExpand"
                Text="Welcome to SearchView!"
                VerticalOptions="CenterAndExpand" />
    
            <Label Text="{Binding Title}" />
        </StackLayout>
    </ContentPage.Content>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 2021-04-11
      • 1970-01-01
      • 2021-07-28
      相关资源
      最近更新 更多