【发布时间】:2020-12-22 18:16:38
【问题描述】:
我想将参数“Trip”传递给导航页面的视图模型。到目前为止,我有这个: 我将从中导航的页面的代码。这是一次旅行的翻转
public sealed partial class TripOverview : Page
{
public TripOverview()
{
this.InitializeComponent();
DataContext = new TripOverviewViewmodel();
}
public void Trip_Detail(object sender, RoutedEventArgs e)
{
Trip selectedTrip = (Trip)TripFlip.SelectedItem;
this.Frame.Navigate(typeof(TripDetail), selectedTrip);
}
}
这是我的旅行详情页面。我想将从 onNavigatedTo 方法获得的参数添加到视图模型中,然后链接到 Datacontext。
public sealed partial class TripDetail : Page
{
public Trip selectedTrip { get; set; }
public TripDetailViewmodel vm = new TripDetailViewmodel();
public TripDetail()
{
this.InitializeComponent();
this.DataContext = vm;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Trip trip = (Trip)e.Parameter;
base.OnNavigatedTo(e);
}
}
所以基本上我想要我的视图模型中的“currentTrip”属性:
public class TripDetailViewmodel
{
public Trip CurrentTrip { get; set; }
public TripDetailViewmodel()
{
}
}
在不使用 mvvm light 的情况下进行设置
这是我的 TripDetail 页面的 XAML
<Page
x:Class="TravelChecker.TripDetail"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TravelChecker"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:viewmodel="using:TravelChecker.Viewmod"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.DataContext>
<viewmodel:TripDetailViewmodel x:Name="tripsDetailVm" />
</Page.DataContext>
<Grid>
<TextBlock x:Name="title" Text="{x:Bind tripsDetailVm.CurrentTrip.Destination.LocationName}"
FontFamily="Segoe UI" FontSize="26.667"
Foreground="Black" Padding="15,20" RenderTransformOrigin="0.318,0.392" />
<TextBox Text="{Binding ElementName=title, Path=Text, Mode=TwoWay}" x:Name="titletxt">
</TextBox>
</Grid>
【问题讨论】:
-
您可以为此页面发布您的 XAML 吗?为了设置它,您需要将视图模型设为属性(而不是字段)并在 XAML 中设置绑定。
-
你能告诉我MVVM light是指MVVM Light Toolkit吗?您可以尝试在 TripDetail 页面的 OnNavigatedTo 中添加代码
vm.CurrentTrip = trip;。如果代码符合您的要求,请告诉我。 -
我会用 XAML 更新帖子。
-
添加该行不起作用,因为 onnavigatedto 被调用晚了。它首先构建页面,然后初始化虚拟机。我想在创建页面之前初始化 vm,或者至少在之后刷新页面