3

我正在嘗試將Windows Phone 8.1 Silverlight應用程序遷移到UWP。我在獲取Main Application UI時出錯。通用Windows平臺(UWP)相當於獲取主應用程序UI

這是Windows Windows Phone 8.1 Silverlight代碼:

Storage storage = ((App.Current.RootVisual as PhoneApplicationFrame).DataContext as Storage); 

這就是我的UWP版本進行:

Storage storage = ((Window.Current.Content as Frame).DataContext as Storage); 

我得到了NullPointerException。有任何想法嗎?

在此先感謝。

編輯

這是我的XAML:

<Page 
x:Class="windows_phone.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" d:DesignWidth="480" d:DesignHeight="768" 
FontFamily="{StaticResource PhoneFontFamilyNormal}" 
FontSize="20" 
Foreground="#FF000000"> 

<!--LayoutRoot is the root grid where all page content is placed--> 
<Grid x:Name="LayoutRoot" Background="Transparent"> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="Auto"/> 
     <RowDefinition Height="*"/> 
    </Grid.RowDefinitions> 

    <!--TitlePanel contains the name of the application and page title--> 

    <!--ContentPanel - place additional content here--> 
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="0,0,0,0"> 
     <WebView 
      x:Name="webView" 
      Margin="0,0,0,0" 
      Grid.Row="1" 
      /> 
    </Grid> 
</Grid> 

這是我的類存儲,保存最後的URI:

namespace windows 
{ 
public class Storage 
{ 
    #region Properties 
    private Uri _lastUri = null; 
    public Uri lastUri 
    { 
     get {return _lastUri;} 
     set 
     { 
      _lastUri = value; 
     } 
    } 
    #endregion 
} 
} 

第二個編輯

代碼,我使用的存儲類:

public sealed partial class MainPage : Page 
{ 

    private Storage storage = null; 

.... 

protected override void OnNavigatedTo(NavigationEventArgs e) 
    { 
     storage = (((Window.Current.Content as Frame).Content as Page).DataContext as Storage); 
     if (Storage.lastUri != null) webView.Navigate(Storage.lastUri); 
     base.OnNavigatedTo(e); 
    } 

    void webView_LoadCompleted(object sender, NavigationEventArgs e) 
    { 
     if (webView.Source.ToString().Contains("login")) 
     { 
      string id = LoadUserIdFromIsolatedStorage(); 
      String[] data = new String[1]; 
      data[0] = id; 
      if (id != null) 
       webView.InvokeScript("WinHelp", data); 
     } 
     progressIndicator.Visibility = Visibility.Collapsed; 
     Storage.lastUri = e.Uri; 
    } 
+0

如果我正確理解你,你想獲得活動框架的DataContext? –

+0

是的,正是如此。 – IrApp

+0

這是從代碼背後的文件或單獨的類撤回? –

回答

2

框架的DataContext的確實是NULL。這是因爲框架將視圖放在另一個內容變量中。那一個將包含您的DataContext

您需要將內容聲明爲頁面。下面是一個例子:

((Window.Current.Content as Frame).Content as Page).DataContext; 
+0

我已經試過你的答案,但我已經有同樣的錯誤。 – IrApp

+0

我稍微修改了一下示例。我忘了添加一些東西。如果它仍然沒有幫助,請爲您的問題添加額外的信息。就像你在應用中使用它的地方一樣(例如:MainPage.xaml.cs)以及你需要它的地方。有了這個,我可以改善我的答案。 –

+0

我已經添加了額外的信息。我寫了我的xaml。該應用程序只包含一個名爲MainPage的頁面。 – IrApp

相關問題