Phi*_*ert 11 c# xaml microsoft-metro windows-8
我有一个自定义Panel,我声明了一个自定义属性来保存内容(我不想使用Children作为内容):
[ContentProperty(Name = "PanelContent")]
public class CustomPanel : Panel
{
public static readonly DependencyProperty PanelContentProperty =
DependencyProperty.Register("PanelContent",
typeof(Collection<UIElement>), typeof(CustomPanel),
new PropertyMetadata(new Collection<UIElement>(), null));
public Collection<UIElement> PanelContent
{
get
{
return (Collection<UIElement>)GetValue(PanelContentProperty);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这样使用时效果很好:
<CustomPanel>
<TextBlock>A</TextBlock>
<TextBlock>B</TextBlock>
</CustomPanel>
Run Code Online (Sandbox Code Playgroud)
但是当我想在ItemsControl中使用面板作为ItemsPanelTemplate时,将忽略ContentProperty属性并将所有内容添加到Children集合,而不是PanelContent集合:
<ItemsControl ItemTemplate="{StaticResource ReviewTemplate}" ItemsSource="{Binding Reviews}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<CustomPanel></CustomPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)
这不是它应该如何工作.根据文件:
ItemsPanelTemplate对象元素应该只包含一个FrameworkElement派生类,该类用作项的根元素.在大多数情况下,这是一个Panel派生类.扩展模板用作已实现项目的父项,并且通常存在多个项目.因此,ItemsPanelTemplate的预期根元素的XAML内容属性应该支持集合,如Panel.Children所做的那样.
负责此任务的面板的GenerateChildren方法看起来(如ILSpy中所示)像
internal virtual void GenerateChildren()
{
IItemContainerGenerator itemContainerGenerator = this._itemContainerGenerator;
if (itemContainerGenerator != null)
{
using (itemContainerGenerator.StartAt(new GeneratorPosition(-1, 0), GeneratorDirection.Forward))
{
UIElement uIElement;
while ((uIElement = (itemContainerGenerator.GenerateNext() as UIElement)) != null)
{
this._uiElementCollection.AddInternal(uIElement);
itemContainerGenerator.PrepareItemContainer(uIElement);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,它总是添加到 this._uiElementCollection,这是支持 Children 属性的字段。
归档时间: |
|
查看次数: |
1832 次 |
最近记录: |