我是一個C#語言的初學者,希望通過這個博客和大家交流學習時發現的問題和學習經驗。與此同時還可以作爲一個督促自己堅持的辦法。希望這個欄目不要斷更。同時我使用的教程是“Head First C#”。
廢話不多說,讓我決定開始寫這篇博客的主要原因是,我在做本書的第一個例程時發現,當程序運行到
private void AddEnemy()
{
ContentControl enemy = new ContentControl();
enemy.Template = Resources["EnemyTemplate"] as ControlTemplate;
AnimateEnemy(enemy, 0, playArea.ActualWidth - 100, "(Canvas.Left)");
AnimateEnemy(enemy, random.Next((int)playArea.ActualHeight - 100),
random.Next((int)playArea.ActualHeight - 100), "(Canvas.Top)");
playArea.Children.Add(enemy);
}
這段代碼時,會出現一個致命的錯誤,錯誤信息如下
在運行時,點擊start按鈕後出現中斷,錯誤信息如下:
“System.Runtime.InteropServices.COMException”類型的異常在 mscorlib.dll 中發生,但未在用戶代碼中進行處理
WinRT 信息: Cannot find
a resource with the given key.
經過我調試後發現,程序會在
enemy.Template = Resources["EnemyTemplate"] as ControlTemplate;
這段代碼運行後,出現強制中斷的情況。然而語句本身看不到任何問題。
於是我檢查了ControlTemplate 這個類的說明,瞭解了使用方法之後,在MainPag.xaml中找到了這個模板的定義。我發現在定義中
<ContentControl Content="ContentControl" HorizontalAlignment="Center" VerticalAlignment="Center" Template="{StaticResource EnemyTemplat}"/>
最後的Template 的標記(姑且讓我這麼叫他)。是EnemyTemplat而不是書上的代碼設計中的EnemyTemplate注意最後一個e。然而這段代碼好像是自動生成的,也許是我不記得了
這裏先留個疑問。那麼問題就好解決了。只需將AddEnemy()中的EnemyTemplate的e去掉就可以了。
這裏還有一些不是很明白的地方,就是我打算直接更改xaml中的template的定義的時候卻會報錯。
第一篇學習筆記,第一次用CSDN有很多不足的地方希望大家指正。