使用MVVM在Silverlight页面之间导航

时间:2012-04-03 16:44:01

标签: c# silverlight mvvm user-controls navigation

我正在Silverlight 4上创建简单的应用程序。 在View的文件夹中我有2个(Silverlight Pages)也在ViewModel中我有2个ViewModel。 在Silverligh项目中,我有UserControl,其中包含一个页面。 我需要使用导航的简单示例。 例如,我单击按钮,在ViewModel中调用一些方法,这个方法将我重定向到另一个Silverligh页面。请帮助我,我受苦3天了,我发现只有非常难的例子,但我很简单。

<UserControl x:Class="WebServerApp.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
             xmlns:pagescol="clr-namespace:SilverlightServerLib.View;assembly=SilverlightServerLib"

    Width="Auto" Height="Auto">

    <Grid x:Name="LayoutRoot" Background="White">
        <pagescol:SettingsPage/>
    </Grid>
</UserControl>

这是一个持有第一页的UserControll,我需要导航到另一个页面。 非常感谢你!

1 个答案:

答案 0 :(得分:2)

你应该使用Navigation框架中的Frame控件(silverlight takeit)。 然后你可以试试这种方法

<Button Content="Click">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <i:EventTrigger.Actions>
                <actions:NavigateAction UriPath="/Home" TargetName="MainFrame" />
            </i:EventTrigger.Actions>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

<navigation:Frame x:Name="MainFrame"                          
                  UriMapper="{StaticResource UriMapper}" />

以及NavigateAction的相应代码:

public class NavigateAction : TargetedTriggerAction<Frame>
{
    public static readonly DependencyProperty UriPathProperty =
        DependencyProperty.Register("UriPath", typeof(string), typeof(NavigateAction), null);

    public string UriPath
    {
        get { return (string)GetValue(UriPathProperty); }
        set { SetValue(UriPathProperty, value); }
    }

    protected override void Invoke(object parameter)
    {
        Target.Navigate(new Uri(UriPath, UriKind.RelativeOrAbsolute));
    }
}

另外,你应该总是使用UriMapper。这是一个很好的做法:

<Application.Resources>
    <sdk:UriMapper x:Key="UriMapper">
        <sdk:UriMapping MappedUri="/Views/TasksView.xaml" Uri="" />
        <sdk:UriMapping MappedUri="/Views/{view}View.xaml" Uri="/{view}" />
    </sdk:UriMapper>
</Application.Resources>
相关问题