考慮下面的XAML文件:爲什麼是X:在ResourceDictionary中所需的控件模板鍵
<Window x:Class="ExpressionVisualizer.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sle="clr-namespace:System.Linq.Expressions;assembly=System.Core"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type sle:BinaryExpression}"/>
<ControlTemplate TargetType="{x:Type ContentControl}"/>
</Window.Resources>
</Window>
這是給下面的編譯錯誤:
All objects added to an IDictionary must have a Key attribute or some other type of key associated with them. Line 10 Position 10.
如果我添加一個x:key
屬性的它編譯ControlTemplate。但是,我不應該那樣做。 ControlTemplate用DictionaryKeyProperty屬性裝飾,指定TargetType作爲key屬性。所以只要我爲ControlTemplate指定一個TargetType,我應該而不是必須指定一個顯式鍵(類似於我沒有在我定義的DataTemplate上指定一個鍵)。
我有第二個和切線相關的問題。如果我在XAML中以這種方式定義了一個ControlTemplate(或者指定了一個鍵),它是否會自動應用於ContentControl類型的所有控件,這些控件不指定另一個模板,還是必須將ControlTemplate嵌入到一個Style爲了發生?
這回答了我的問題的第二部分。我知道我需要指定一個x:Key,如果我想在文檔的其他地方引用該模板,但省略它不應該導致編譯錯誤。 – luksan 2012-03-03 20:52:11
我已經更新了我的答案。它接縫'DictionaryKeyProperty'沒有做它應該是... – nemesv 2012-03-03 21:00:24
DictionaryKeyProperty的問題似乎不會影響所有類型,因爲該屬性按照DataTemplate中指定的方式工作。連接問題是從2009年開始的。我想我只是把它寫成WPF中的另一件事情,它不起作用,從來沒有經過徹底的測試。每當我嘗試在WPF中開發某些東西時,我都會遇到這些類型的問題。這絕不會出現在Windows窗體上,一切正常。我真的認爲(或許是希望)他們將在4.0版本中讓WPF更具可預測性/可用性。 – luksan 2012-03-03 21:27:07