我遇到了使用DataTemplate鍵的奇怪行爲:當通過x:Type指定DataType,並且通過x:Static reference指定了x:Key時,將忽略x:Key。我寫了示例應用程序來說明它。使用x指定時,將忽略DataTemplate鍵:靜態
XAML資源:
<DataTemplate DataType="{x:Type wpfApplication1:TestDto}" x:Key="{x:Static wpfApplication1:DataKeys.TestDtoKey}" />
<DataTemplate x:Key="{x:Static wpfApplication1:DataKeys.TestDtoKey2}" />
<DataTemplate DataType="{x:Type wpfApplication1:TestDto}" x:Key="TestKey3" />
<DataTemplate DataType="wpfApplication1:TestDto" x:Key="{x:Static wpfApplication1:DataKeys.TestDtoKey4}" />
C#:
public class TestDto {}
public static class DataKeys
{
public static string TestDtoKey = "TestKey";
public static string TestDtoKey2 = "TestKey2";
public static string TestDtoKey4 = "TestKey4";
}
啓動應用程序,請參見調試this.Resources.Keys:
{DataTemplateKey(WpfApplication1.TestDto)} object {System.Windows.DataTemplateKey}
"TestKey2" object {string}
"TestKey3" object {string}
"TestKey4" object {string}
正如你所看到的,在第一種情況下x:鍵被忽略!
有人可以解釋發生了什麼? 文檔(http://msdn.microsoft.com/en-us/library/system.windows.datatemplate.datatype.aspx)明確指出,設置x:Key會將資源鍵設置爲您在其中指定的任何值。
與bug非常相似。也許你應該嘗試寫connect.microsoft.com的反饋? –