[英]WPF DataTemplate Binding to Content without Path - is this a bug?
我在理解以下行为时遇到问题(在.Net 4.0中测试)
首先:下面的示例按我的预期工作:它在Button中显示一个CheckBox。
C#:
DataContext = new CheckBox();
XAML:
<Button Content="{Binding}"/>
在带有路径的ItemsControl(“ MyProperty”)中,它也可以工作:
C#:
DataContext = new { MyList = new List<object>() { new { MyProperty = new CheckBox() } } };
XAML:
<ItemsControl ItemsSource="{Binding Path=MyList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Path=MyProperty}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
但是在没有路径的ItemsControl内部,它将替换Button并仅显示CheckBox:
C#:
DataContext = new { MyList = new List<CheckBox>() { new CheckBox() } };
XAML:
<ItemsControl ItemsSource="{Binding Path=MyList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
为什么这个例子不起作用? 这是WPF中的错误吗? 非常感谢您的帮助!
这不是错误。 DataTemplate
不适用于ContentControls
。 这就是为什么您的示例代码在ItemsControl
中的项目的DataContext
是CheckBox
时不起作用,而在DataContext
是object
时却起作用的原因。
您不应在DataContext
/ view模型中定义用户界面元素。
我不会将描述的行为视为WPF / XAML错误。
ItemsControl(与ListView或ListBox相比)没有默认的ItemContainer(作为ListViewItem或ListboxItem)。 使用ListBox或ListView,您的示例将起作用。
如果您有一个List<Textbox>
作为ItemsSource
,则ItemsControl
将ItemsSource
项目用作ItemContainers,因此TextBoxes将是ItemContainers,您将成为
System.Windows.Data Error: 26 : ItemTemplate and ItemTemplateSelector are ignored for items already of the ItemsControl's container type; Type='CheckBox'
在调试输出中,因此您将忽略DataTemplate(如果不指定ItemTemplate,则会遇到相同的问题)。
要解决此问题,您可以从ItemsControl
派生并重写IsItemItsOwnContainerOverride方法:
确定指定的项目是否是(或有资格成为)自己的容器
非常感谢你的回答!
我不知道方法IsItemItsOwnContainerOverride。 如果我重写它并始终返回true,那么所有工作都将如我所料。
我知道,这种实施方法不是最佳方法。 但是现在我明白了这种行为,我很高兴;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.