我在使用DataTemplate键时遇到了奇怪的行为:当通过x:Type指定DataType,且通过x:Static引用指定x:Key时,x:Key会被忽略。我创建了一个示例应用程序来说明。
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:Key被忽略了!
有人能解释一下发生了什么吗? 文档(http://msdn.microsoft.com/en-us/library/system.windows.datatemplate.datatype.aspx)清楚地说明设置x:Key将把资源键设置为您在其中指定的任何内容。