簡體   English   中英

綁定app.xaml以在C#中查看WPF

[英]Binding app.xaml to view WPF in c#

我使用MVVM框架,並在網上獲得了本教程: https : //code.msdn.microsoft.com/windowsdesktop/How-to-use-MVVM-Pattern-0e2f4571http://www.c-sharpcorner.com/UploadFile / raj1979 /簡單MVVM圖案在-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中而不是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訪問名稱空間中包含的類型。

您可以做的是代替在app.xaml.cs中設置數據上下文,只需掛接主窗口的已加載事件並添加以下代碼即可。

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

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

這應該工作。 不要忘記從App.xaml.cs中刪除代碼。 謝謝

因此,在您的情況下,您需要在該主窗口內加載一個主窗口。 您可以做的是在主窗口中添加一個框架,例如

 <Frame x:Name="myFrame"/>

然后在mainwindow加載的事件內添加以下代碼

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

就像我們要添加一個框架並將您的視圖加載到該框架一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM