ItemsControl的派生类上的WPF OnApplyTemplate不是';t调用
本文关键字:调用 不是 OnApplyTemplate 派生 WPF ItemsControl | 更新日期: 2023-09-27 17:58:20
标题基本上指出了这一点。我读过其他与同一问题相关的博客和帖子,但没有一个提供的解决方案对我有效
以下是我的代码的简化:
<!-- CustomItemsControl.xaml -->
<ItemsControl x:Class="myNamespace.CustomItemsControl"
xmlns:local="clr-namespace:myNamespace">
<ItemsControl.Resources>
<Style TargetType="{x:Type local:CustomItemsControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomItemsControl}">
<Grid x:Name="MyItemsHost" Background="{TemplateBinding Background}" IsItemsHost="True"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ItemsControl.Resources>
</ItemsControl>
// CustomItemsControl.xaml.cs
namespace myNamespace
{
public partial class CustomItemsControl : ItemsControl
{
public CustomItemsControl()
{
this.DefaultStyleKey = typeof(CustomItemsControl);
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var MyItemsHost = (Grid)base.GetTemplateChild("MyItemsHost");
}
}
}
我做错了什么?
我以前从未见过这样做,我在Generic.xaml中定义了模板,因为这是Visual Studio在执行项目->添加自定义控件(WPF)时生成的模板。
通过在构造函数中调用InitializeComponent();
,可以使发布的代码正常工作。此外,文档中还说应该使用Template.FindName("MyItemsHost",this)
而不是GetTemplateChild
。如果控件可能需要网格以外的其他布局,则可能需要使用ItemsPresenter并设置ItemsPanelTemplate。
根据自定义控件的派生内容,您可能无法对其调用InitializeComponent()。例如,ContentControl不提供InitializeComponent。
如果你检查这个线程,你会发现OnApplyTemplate从未被调用的原因,是因为你将项目定义为类库,而不是自定义控件库。Visual Studio向AssemblyInfo.cs添加了额外的信息,以告诉运行时在哪里可以找到控件的模板。
如果您将以下代码添加到AssemblyInfo.cs文件中,它应该开始正常运行:
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]