2015-11-10 78 views
0

所以我試過以下UWP Accessing Frame for page navigation through Usercontrol an Object? 但我得到一個空指針。從另一個類的框架內改變頁面

我有一個帶有分割視圖,框架和漢堡菜單的主頁。從這裏我控制加載到框架中的頁面。
我也有一個配置文件視圖,我想調用一個新的視圖,當用戶點擊一個按鈕。讓我補充代碼:

的MainPage:

public sealed partial class MainPage : Page 

{ 

    Profile profile = new Profile(); 

    public MainPage() 
    { 
     this.InitializeComponent(); 
     MyFrame.Navigate(typeof(Financial)); 
     BackButton.Visibility = Visibility.Collapsed; 
     Title.Margin = new Thickness(68,0,0,0); 

     profile.OnNavigateParentReady += OnCreateUser; 

    } 

.... 



    public void OnCreateUser(object sender, RoutedEventArgs e) 
    { 
     if (MySplitView.Content != null) 
      ((Frame)MySplitView.Content).Navigate(typeof(CreateUser)); 
     Title.Text = "Create User"; 
     BackButton.Visibility = Visibility.Visible; 
     Title.Margin = new Thickness(0, 0, 0, 0); 

    } 

} 

和配置文件:

public sealed partial class Profile : Page 

{ 

    public delegate void MyEventHandler(object source, RoutedEventArgs e); 

    public event MyEventHandler OnNavigateParentReady; 


    private string _profileName; 
    private string _password; 

    private Dictionary<string, string> usersDictionary = new Dictionary<string, string>(); 

    public Profile() 
    { 
     this.InitializeComponent(); 
     usersDictionary.Add("Casper", "12345"); 
    } 

    private void Login_Click(object sender, RoutedEventArgs e) 
    { 
     _profileName = ProfileName.Text; 
     _password = PasswordBox.Password; 

     if (usersDictionary.ContainsKey(_profileName)) 
     { 
      if (usersDictionary[_profileName] == _password) 
      { 
       ProfileName.Text = "LOGIN SUCCES!"; 
      } 
     } 
     else 
     { 

     } 
    } 

    private void CreateUser_Click(object sender, RoutedEventArgs e) 
    { 
     OnNavigateParentReady(sender, e); 
    } 
} 

我可以改變使用Frame.navigate沒有問題的框架,但我想編輯的標題以及保證金和所有其他OnCreateUser呢。我該如何解決這個問題?

編輯:我應該說,我得到一個空指針在這條線:OnNavigateParentReady(sender, e);

回答

2

那空引用異常被拋出,因爲OnNavigateParentReady事件沒有監聽的是,當你的CreateUser控件調用Click事件。你應該嘗試以下操作:

if (OnNavigateParentReady != null) 
{ 
    OnNavigateParentReady(sender, e); 
} 

此外,您在MainPage類中創建profile對象 - 在使用它?它有沒有顯示在任何地方?看起來好像該對象不是您的應用中顯示的對象。相反,其他一些Profile正在使用!

您的MainPage類的profile成員字段可能不是Page當您導航時實際顯示的。嘗試在實際顯示的頁面對象Profile上設置事件偵聽器。

+0

它解決了崩潰,但框架並沒有改變,似乎沒有正確調用方法。 – Evilunclebill

+0

這裏使用它:'profile.OnNavigateParentReady + = OnCreateUser;' – Evilunclebill

+0

我對C#相當新,所以不太確定如何設置事件監聽器? – Evilunclebill

相關問題