2011-05-01 119 views
5

我正嘗試在Windows Phone 7中爲我的應用創建一個設置頁面。我創建了AppSettings類,並從我的MainPage.xaml中引用它。這是我的代碼:Xaml無法創建「X」的實例

<phone:PhoneApplicationPage 
    x:Class="Shapes4Kids.MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" 
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:local="clr-namespace:ShapesSettings;assembly=Shapes4Kids" 
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="696" 
    FontFamily="{StaticResource PhoneFontFamilyNormal}" 
    FontSize="{StaticResource PhoneFontSizeNormal}" 
    Foreground="{StaticResource PhoneForegroundBrush}" 
    SupportedOrientations="Portrait" Orientation="Portrait" 
    shell:SystemTray.IsVisible="True"> 
    <phone:PhoneApplicationPage.Resources> 
     <local:AppSettings x:Key="appSettings"></local:AppSettings> 
    </phone:PhoneApplicationPage.Resources> 

但在這裏我指的AppSettings的行(本地:AppSettings的線),我得到一個錯誤消息,指出「不能創建的AppSettings的實例」。

+0

我有完全相同的問題。 – 2011-12-29 19:58:16

回答

4

這是因爲實例化ApplicationsSettings會引發異常。如果將以下內容添加到構造函數中,則應該沒問題;

try 
{ 
    settings = IsolatedStorageSettings.ApplicationSettings; 
} 
catch (System.IO.IsolatedStorage.IsolatedStorageException e) 
{ 
    // handle exception 
} 
+1

微軟需要更新他們的「如何」來反映這一點! http://msdn.microsoft.com/en-us/library/ff769510(v=vs.92) – jedmao 2012-06-10 03:49:46

3

對於像這樣在xaml中引用的對象,它們需要有一個默認的無參數構造函數。我會仔細檢查是這種情況。

其他潛在問題可能是構造函數中拋出的異常。

+0

我檢查了一下,我有一個無參數的構造函數。 – 2011-05-02 00:01:16

+1

我看到我的應用程序運行時沒有問題,即使當我的應用程序停止時,在VS中的錯誤列表上看到此錯誤時也是如此。也許它正在運行時解決?我不確定.... – 2011-05-02 02:57:25

0

一個可能的原因也可能是失敗的依賴項屬性初始化。

我曾在一類下面的代碼,我試圖在XAML實例:

public static readonly DependencyProperty ListViewObjectProperty = DependencyProperty.Register(
                           "ListViewObject", 
                           typeof(ListView), 
                           typeof(WidthConverter), 
                           new UIPropertyMetadata(0)); 

...其中這種依賴性屬性是打算抱着ListView的參考。但VS默認的「propdp」代碼片段生成了這個「新的UIPropertyMetadata(0)」,這在參考變量的情況下有點錯誤。它應該是「新的UIPropertyMetadata(null)」。

更改這個固定的問題給我。出於某種原因,我在運行時沒有收到任何可見的異常。