ItemsControl的:如何使用内ItemsPanelTemplate FindName访问面板 [英] ItemsControl: How To Use FindName within ItemsPanelTemplate to access Panel
问题描述
<Style TargetType="{x:Type local:CustomItemsControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<ScrollViewer>
<ItemsPresenter x:Name="PART_Presenter"/>
</ScrollViewer>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<StackPanel x:Name="PART_StackPanel" IsItemsHost="True"/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
试图访问的StackPanel当孩子被更改设置活动。
Trying to access the StackPanel to set Events when children are changed.
[TemplatePartAttribute(Name = "PART_StackPanel", Type = typeof(StackPanel))]
[TemplatePartAttribute(Name = "PART_Presenter", Type = typeof(ItemsPresenter))]
public class CustomItemsControl: ItemsControl
{
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var presenter = (ItemsPresenter)this.Template.FindName("PART_Presenter", this);
var stackPanel = (StackPanel)this.ItemsPanel.FindName("PART_StackPanel",this);
}
}
获取当我试图找到StackPanel的异常。
Get Exception when I try to locate the StackPanel.
出现InvalidOperationException:
InvalidOperationException:
这操作只适用于有此模板元素应用。
This operation is valid only on elements that have this template applied.
请告知,如果有找到一个ItemsPanelTemplate内TemplatePart的一种方式。当我应该期待当应用ItemsPanelTemplate知道?
Please advise if there is a way to find a TemplatePart within an ItemsPanelTemplate. And when should I expect to know when the ItemsPanelTemplate is applied?
推荐答案
另一种方法是调用。 ApplyTemplate,都()
在ItemsPresenter同时还在ItemControl的 OnApplyTemplate
方法。然后调用 .FindName
会成功的。
Another option is to call .ApplyTemplate()
on the ItemsPresenter while still in the ItemControl's OnApplyTemplate
method. Then the call to .FindName
will succeed.
[TemplatePartAttribute(Name = "PART_StackPanel", Type = typeof(StackPanel))]
[TemplatePartAttribute(Name = "PART_Presenter", Type = typeof(ItemsPresenter))]
public class CustomItemsControl : ItemsControl
{
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var presenter = (ItemsPresenter)this.Template.FindName("PART_Presenter", this);
presenter.ApplyTemplate();
var stackPanel = (StackPanel)this.ItemsPanel.FindName("PART_StackPanel", presenter);
}
}
这篇关于ItemsControl的:如何使用内ItemsPanelTemplate FindName访问面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!