[英]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.