绑定app.xaml在c#中查看WPF

Binding app.xaml to view WPF in c#

我使用 MVVM 框架并在网上找到了这个教程:https://code.msdn.microsoft.com/windowsdesktop/How-to-use-MVVM-Pattern-0e2f4571 and http://www.c-sharpcorner.com/UploadFile/raj1979/simple-mvvm-pattern-in-wpf/

现在,我的问题是:

即使没有语义错误,我也无法显示 mainpage.xaml。这是我在 app.xaml.cs:

上的代码
protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    BasicWPF.View.MainPage window = new MainPage();
    UserViewModel VM = new UserViewModel();
    window.DataContext = VM;
    window.Show();
}

谁能帮帮我?谢谢你的帮助! :)

感谢所有帮助过的人。

[已解决]

将 app.xaml 中的 startupuri 更改为您要加载页面的位置。就我而言

1:我改:

StartupUri="View/MainPage.xaml"

2:在app.xaml.cs中,我输入了这段代码:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    BasicWPF.View.MainPage window = new MainPage();
    UserViewModel VM = new UserViewModel();
    window.DataContext = VM;
}

从我之前的代码中删除这段代码:window.show();因为它从 app.xaml 和 app.xaml.cs 启动了两次页面。为防止这种情况,请删除:window.show();

再次感谢! :)

你可以做的不是在 app.xaml.cs 中设置数据上下文,而是连接 main window 的加载事件并添加以下代码。

   public MainWindow()
    {
        InitializeComponent();
        this.Loaded += MainWindow_Loaded;
    }

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        UserViewModel VM = new UserViewModel();
        this.DataContext = VM;
    }  

这应该有效。不要忘记从 App.xaml.cs 中删除代码。 谢谢

在 app.xaml 中设置起始页,而不是 app.xaml.cs 文件 - 在 Application 标记中,如果没有 属性 StartupUri - 添加一个并将其值设置为您的页面名称,这样页面将在您的应用程序启动后立即自动显示。它应该看起来像这样:

<Application x:Class="WpfApplication1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainPage.xaml">

我考虑到您这样做是因为您希望设置页面的 DataContext,但是有一种更好的方法来设置您页面的 DataContext,即直接将其设置到您的 XAML代码。这是一个例子:

<Page x:Class="WpfApplication1.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525" >
    <Page.DataContext>
        <local:UserViewModel/>
    </Page.DataContext>

xmlns:local是一个前缀映射到你为它设置的命名空间。有了这个,您就可以使用前缀访问命名空间中包含的类型 - local:UserViewModel.

所以在你的情况下你有一个主 window 在主 window 里面你需要加载页面。 你可以做的是在你的 mainwindow 中添加一个框架,比如

 <Frame x:Name="myFrame"/>

然后在 mainwindow 加载事件中添加以下代码

  void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        UserViewModel VM = new UserViewModel();
        this.DataContext = VM;
        myFrame.Content = new MainPage();      
    }

这就像我们正在添加一个框架并将您的视图加载到该框架。