【发布时间】:2019-12-20 01:54:36
【问题描述】:
我有一个简单的问题。我正在尝试在 xamarin 中创建我的跨平台应用程序,这是场景。
我有一个页面,上面有住宿清单。我的想法是,当我点击一个住宿时,它会打开一个包含更多详细信息的新页面。此事件涵盖了它:
private void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
var Odabrani = e.Item;
PropertyInfo pi = Odabrani.GetType().GetProperty("SmjestajId");
int id = Convert.ToInt32(pi.GetValue(Odabrani,null).ToString());
Application.Current.MainPage = new SmjestajViewPage(id);
}
SmjestajViewPage 将是打开的页面,显然我需要该住宿的 ID 来获取有关它的相关信息。这很好用,我得到了正确的 ID。
这是我目前所拥有的 xaml.cs 文件:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SmjestajViewPage : ContentPage
{
private int _Id;
SmjestajVM viewmodel = null;
public SmjestajViewPage()
{
InitializeComponent();
}
public SmjestajViewPage(int id)
{
InitializeComponent();
_Id = id;
BindingContext = viewmodel = new SmjestajVM(id);
}
}
这是 SmjestajVM 到目前为止的样子:
public class SmjestajVM : BaseViewModel
{
int _SmjestajId;
public SmjestajVM(int Id)
{
_SmjestajId = Id;
}
}
但是,除非我添加无参数构造函数,否则此选项不会作为 xaml 编辑过程中的选项之一出现。到目前为止,这就是我的 xaml 文件的样子:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ViewModels="clr-namespace:RS2_Booking.MobileApp.ViewModels"
mc:Ignorable="d"
x:Class="RS2_Booking.MobileApp.Views.SmjestajViewPage"
>
<ContentPage.BindingContext>
<ViewModels:SmjestajVM></ViewModels:SmjestajVM>
</ContentPage.BindingContext>
<ContentPage.Content>
<StackLayout>
<Label Text="Welcome to Xamarin.Forms!"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
问题在于这一行:
<ContentPage.BindingContext>
<ViewModels:SmjestajVM></ViewModels:SmjestajVM>
</ContentPage.BindingContext>
如何编写它才能正常工作?我尝试了 SmjestajVM(Id) 和 SmjestajVM("Id") 但都没有成功。
【问题讨论】:
-
你不能在 XAML 中用 vanilla XF 做到这一点。您要么需要在代码隐藏中完成,要么使用 MVVM 框架
-
你能解释一下你所说的代码隐藏是什么意思吗?
-
xaml.cs 文件