我遇到了DataTemplate键的奇怪行为:当通过x:Type指定DataType时,x:通过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会将资源键设置为您在其中指定的任何内容 .
2 回答
Update -
Microsoft已经接受它是XAML编译器中的一个错误,他们并没有解决这个问题 . 来自微软的报价 -
x:此处不忽略键,但在第一种情况下设置为
DataTemplateKey(WpfApplication1.TestDto)
. 如果没有键值,则不能在“资源”部分下声明资源 .如您所见,该键自动设置为
DataTemplateKey(WpfApplication1.TestDto)
.来自MSDN -
不知何故,如果您使用
bind x:Key with static value
而不是硬编码字符串,它会得到defined as default template for that dataType
,因此密钥设置为DataTemplateKey(WpfApplication1.TestDto)
.您可以通过将另一个DataTemplate添加到仅包含DataType设置的资源来验证,即
<DataTemplate DataType="{x:Type wpfApplication1:TestDto}"/>
.它将编译正常,但会抛出运行时错误
我并不害羞,但会尝试将{get; set;}附加到 class 中的每个属性 . WPF中的一些工作人员(即Binding)在没有它们的情况下不起作用 . 可能在这里是同一个故事......