[英]How to pass a parameter to the viewmodel of the navigated page without mvvm light
我想將參數“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 方法獲取的參數添加到 viewmodel,然后將其鏈接到 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>
當您使用{x:Bind}實現數據綁定時,默認源是頁面而不是DataContext
。 {x:Bind}將在您頁面的代碼隱藏中查找屬性、字段和方法。 要將您的視圖 model 公開給{x:Bind} ,您通常需要向頁面的代碼隱藏添加新字段或屬性。
但是如果你使用{Binding}來實現數據綁定, {Binding}將需要DataContext
。
因此,您可以 select 在 XAML 的tripsDetailVm
標記中創建的Page.DataContext
或在代碼隱藏中創建的vm
作為綁定源。 但是,無論您 select 是哪個綁定源,都需要將CurrentTrip
屬性設置為trip
。
當您使用tripsDetailVm
作為DataContext
時,您需要添加代碼tripsDetailVm.CurrentTrip = trip;
到OnNavigatedTo
方法。 然后{x:Bind}可以在頁面中找到tripsDetailVm.CurrentTrip.Destination.LocationName
並且{Binding}可以在DataContext
中找到title
(即tripsDetailVm
)。 雖然vm
的初始化晚於頁面構建,但是沒關系。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.