[英]Binding Page with ViewModel (MVVM) on Universal Windows App
我需要在 Xaml wpf 頁面中的 Frame 控件上綁定一個頁面。 我的 xaml 頁面:
<Page
x:Class="MyPro.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MyPro"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:viewmodel="using:MyPro.ViewModel"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:x1="using:System"
mc:Ignorable="d">
<Page.DataContext>
<viewmodel:PagerViewModel x:Name="PagerViewModel"></viewmodel:PagerViewModel>
</Page.DataContext>
<Frame
VerticalContentAlignment="Stretch"
HorizontalContentAlignment="Stretch"
Name="frameMainPage"
DataContext="{Binding Source=Pager.Page, Mode=TwoWay}">
</Frame>
我試過使用這個(但我不知道它是否正確):
DataContext="{Binding Source=Pager.Page, Mode=TwoWay}"
但不起作用。
我的視圖模型,我調用 Pager 來設置新頁面:
class PagerViewModel
{
public PagerViewModel()
{
m_pager = new Pager();
}
public static Pager m_pager;
public Pager Pager
{
get
{
return m_pager;
}
set
{
m_pager = value;
}
}
}
和我的模型,我設置頁面模式是這樣的:
public class Pager : INotifyPropertyChanged
{
private Page m_page;
public Page Page
{
get
{
return m_page;
}
set
{
m_page = value;
OnPropertyChanged("Page");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
我需要從代碼中的每個部分更改這樣的頁面:
PagerViewModel.m_pager.Page = new MyPage();
如何在通用 Windows 應用程序 UWP 上執行此操作?
我是這樣解決的:
DataContext="{Binding Path=Pager.Page, Mode=TwoWay}"
您必須在 UWP 上的通用應用程序中使用 Path 而不是 Source
綁定到Frame
DataContext
不會做任何事情。 DataContext
基本上只是告訴控件它的綁定的相對路徑指的是什么,但不會引起任何行為(或者至少這適用於內置控件)。
在您的情況下,您需要綁定到Frame
控件的Content
屬性:
<Frame Content="{Binding Pager.Page}" />
這對我有用,我已經在空白解決方案上使用您的代碼和主頁上的附加按鈕對其進行了測試:
XAML
<Page
x:Class="App4.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App4"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.DataContext>
<local:PagerViewModel x:Name="PagerViewModel"></local:PagerViewModel>
</Page.DataContext>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Frame Width="500" Height="500" Content="{Binding Pager.Page}" />
<Button Click="ButtonBase_OnClick">Click</Button>
</Grid>
</Page>
代碼隱藏
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
((PagerViewModel)DataContext).Pager.Page = new SecondPage();
}
}
SecondPage
是一個空頁面,我將其設置為藍色背景,以便能夠清楚地看到它顯示在Frame
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.