C#UWP MVVM在另一个视图中注入一个视图



嗨,我有一个xaml文件,其中有一个NavigationView和NavigationViewItems。在NavigationView中,我有一个ScrollViewer,我想在其中注入一个视图。这是xaml:

<Page
x:Class="ToolBoxApp.Views.AudioHomeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ToolBoxApp.Views"
xmlns:viewmodels="using:ToolBoxApp.ViewModels"
xmlns:mainview="clr-namespace:ToolBoxApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:i="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<!--<Page.DataContext>
<viewmodels:AudioHomeViewModel/>
</Page.DataContext>-->

<Grid>
<NavigationView x:Name="navigationViewControl" 
IsBackEnabled="true"
>
<i:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="ItemInvoked">
<core:EventTriggerBehavior.Actions>
<core:InvokeCommandAction Command="{Binding NavigateToTextToSpeechView}" />
</core:EventTriggerBehavior.Actions>
</core:EventTriggerBehavior>
</i:Interaction.Behaviors>
<NavigationView.MenuItems>
<NavigationViewItem Icon="MusicInfo" Content="Text to Speech"/>
<NavigationViewItem Icon="MusicInfo" Content="Youtube to Mp3"/>
</NavigationView.MenuItems>
<ScrollViewer>
<Frame x:Name="ContentFrame"/>
</ScrollViewer>

</NavigationView>
</Grid>
</Page>

到目前为止,我有一个导航服务,可以导航到不同的视图:

public class NavigationService : INavigationService
{
public void GoBack()
{
var frame = (Frame)Window.Current.Content;
frame.GoBack();
}
public void Navigate(Type sourcePage)
{
var frame = (Frame)Window.Current.Content;
frame.Navigate(sourcePage);    
}
public void Navigate(Type sourcePage, object parameter)
{
var frame = (Frame)Window.Current.Content;
frame.Navigate(sourcePage, parameter);
}
public void NavigateScrollViewer(Type sourcePage, Type injectPage)
{
var frame = (Frame)Window.Current.Content;

var page = frame.CurrentSourcePageType;
}
}

NavigatScrollViewer方法应该以通用的方式实现这一点,因为整个应用程序都会使用它。我会有不同的窗口,比如上面的xaml文件,我想在那里将视图注入ScrollViewer框架。有没有一种方法可以在代码中引用这个ScrollViewer,然后通过NavigationService将其Frame设置为我想要指定的视图?感谢您的帮助。感谢

C#UWP MVVM在另一个视图中注入一个视图

如果使用MVVM设计,则需要将FrameSourcePageType属性与ViewModel的页面类型属性绑定。您只需要更新此页面类型属性,Frame内容就会更新。

以下是您可以参考的示例代码。

有没有办法在代码中获取对此ScrollViewer的引用,然后将其Frame设置为我想通过NavigationService指定的视图?

另一种方法是将ContentFrame实例传递给NavigationService。首先,您需要为NavigationService类添加新的框架属性。然后用MyFrame替换您的代码帧。

public class NavigationService
{
private Frame MyFrame { get; set; }
public NavigationService(Frame frame)
{
MyFrame = frame;
}
}

Usgae

var navService = new NavigationService(ContentFrame);

上面的设计参考了Windows Template StudioNavigationService,这是一个完整的实现,你可以在shell页面中找到NavigationService的初始化过程。

ViewModel.Initialize(shellFrame, navigationView, KeyboardAccelerators);

最新更新