使用mvvm在xamarin表单的视图之间传递数据 [英] Passing data between view in xamarin forms using mvvm
问题描述
我正在尝试在页面之间导航并同时绑定数据.
I'm trying to navigate between pages and bind data at same time.
这是我尝试过的:
public ICommand GetIdeasCommand
{
get
{
return new Command(async () =>
{
Ideas = await _apiServices.GetIdeasAsync();
await Application.Current.MainPage.Navigation.PushAsync(new IdeasSinglePage(Ideas));
});
}
}
假设想法是我从json获得的数组的列表.但是这种方法对我没有帮助,因为我得到了空白页.另外,如果我在页面内调用此函数,一切都很好. 这篇文章给了我一个主意:
It is supposed the Ideas is a list of arrays I get from the json. But this approach is not helping me since I get a blank page. Also if I call this function inside the page everything is fine. This post gave me an idea : How to pass a parameter from one Page to another Page in Xamarin.Forms?
我的观点:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Ideas.Pages.IdeasSinglePage"
xmlns:vm="clr-namespace:Ideas.ViewModel;assembly=Ideas"
Title="My Page">
<ContentPage.BindingContext>
<vm:IdeasViewModel/>
</ContentPage.BindingContext>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="20, 10">
<Label Text="{Binding Ideas}"
FontSize="12"
TextColor="RoyalBlue"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
后面的代码:
public partial class IdeasSinglePage : ContentPage
{
public IdeasSinglePage(List<Models.Ideas> ideas)
{
InitializeComponent();
this.BindingContext = new IdeasSinglePage(ideas); //the app breaks here
}
}
谢谢.
推荐答案
您缺乏对BindingContext的理解.通常,您将ViewModel绑定到BindingContext.您在这里做什么
Your understanding of BindingContext is lacking. Usually you bind a ViewModel to a BindingContext. What you're doing here
this.BindingContext = new IdeasSinglePage(ideas); //the app breaks here
没有道理.
您要将要加载的页面作为上下文传递吗?只需完全删除此行.由于您在最近的评论中说过您不希望ViewModel开始,因此您在CodeBehind中将要做的是:
You are passing as context the page you want to load ? Just delete this line completely. Since in your recent comments you said you didn't want a ViewModel to begin with, what you will do in your CodeBehind is:
public partial class IdeasSinglePage : ContentPage
{
public IdeasSinglePage(List<Models.Ideas> ideas)
{
InitializeComponent();
listViewName.ItemsSource = ideas;
}
}
然后在xml中为listView命名.您需要使用此名称来引用后面代码中的列表.
And in your xml you give your listView a Name. You need this Name for referencing the list on code behind.
希望有帮助
这篇关于使用mvvm在xamarin表单的视图之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!