【问题标题】:Changing page from another page in main window wpf mvvm c#从主窗口中的另一个页面更改页面 wpf mvvm c#
【发布时间】:2017-05-31 17:39:23
【问题描述】:

我正在为 wpf 使用 mvvmlight 框架。 我有放置框架的主窗口(firstLoadedPage 只是一个示例):

        <Frame Source="firstLoadedPage" />

当我点击按钮时,我想将我的页面更改为另一个页面

第一个加载页面

但我不知道如何实现它。 我已经尝试将这样的属性绑定到框架源:

public static string _myFrameSourcePath = firstLoadedPage
public string MyFrameSourcePath
{
    get { return _myFrameSourcePath; }
    set {
       _myFrameSourcePath = value;
       RaisePropertyChanged("MyFrameSourcePath");
    }
}

然后在我单击 firstLoadedPage 中的按钮时更改 _myFrameSourcePath 的值。它不起作用,所以我尝试将 MyFrameSourcePath 更改为静态,然后在 Page 中更改 MyFrameSourcePath 的值而不是 _myFrameSourcePath。它也不起作用。

当我单击此页面内的按钮将当前页面更改为另一个页面时,有人可以告诉我如何更改放置在 MainWindow 框架源中的页面吗?

【问题讨论】:

  • 当你写&lt;Frame Source="firstLoadedPage" /&gt;的时候,你这里是不是少了一个绑定?它应该类似于&lt;Frame Source="{Binding MyFrameSourcePath}" /&gt;。此外,请确保您设置了公共MyFrameSourcePath 属性,该属性也将调用属性更改通知,而不是私有_myFrameSourcePath。在相关说明中,我不确定这是否是同一件事,但我不久前写了this answer 关于使用 MVVM 导航...也许它会帮助您朝着正确的方向前进?
  • 重点是这只是一个例子。我之前将来自 Frame 的 Souce 与 MainWindowViewModel 中实现的属性绑定。我想通过单击 MyPage.xaml 中的按钮从 MainWindowViewModel 覆盖此属性,这应该更改我在 Source 中的 uri 路径,但即使对于静态变量它也不起作用。

标签: c# wpf xaml mvvm


【解决方案1】:

你可以这样做。下面是一个示例 Xaml

<Grid>
    <StackPanel Orientation="Vertical">
        <TextBlock>Outside area of frame</TextBlock>
        <Frame Name="FrameWithinGrid"  Source="{Binding FrameSource}">
        </Frame>
        <Button x:Name="button1" Height="23" Margin="114,12,25,0" Command="{Binding GoToCommand}"   
            VerticalAlignment="Top" >Navigate to Msdn
        </Button>
    </StackPanel>


</Grid>

在您的 ViewModel 中,一些示例代码例如:

      private Uri _frameSource = new Uri("http://www.google.com", UriKind.Absolute);
      public Uri FrameSource
      {
         get { return _frameSource;}

         set
         {
            _frameSource = value;
            OnPropertyChanged("FrameSource");
         }
      }

      public ICommand GoToCommand
      {
         get
         {
            return new DelegateCommand(ExecuteGoTo);
         }
      }

      private void ExecuteGoTo()
      {
         FrameSource = new Uri("http://www.msdn.com", UriKind.Absolute);
      }

仅此而已。确保您的视图模型实现了 INotifyPropertyChanged。如果您使用的是 MVVM Light,请将 DelegateCommand 更改为 RelayCommand

【讨论】:

  • 我想做一些类似于您的回答 NoahV 的事情,但在您的解决方案中,我正在使用此 window.xaml 中的按钮更改 window.xaml 中的页面。我想通过单击 page.xaml 中的按钮来更改页面,应该更改我的 windowviewmodel 中的属性 URI。
  • 你应该为page.xml创建一个相应的视图模型,设置按钮的Command为例如ExecuteCommand,在page.xml的那个视图模型中,如上声明ICommand
猜你喜欢
  • 2014-10-05
  • 2021-12-10
  • 2014-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
相关资源
最近更新 更多