C# ItemsControl的派生类上的WPF OnApplyTemplate为';我没打电话

C# ItemsControl的派生类上的WPF OnApplyTemplate为';我没打电话,c#,wpf,.net-4.0,itemscontrol,C#,Wpf,.net 4.0,Itemscontrol,标题基本上指出了这一点。我读过其他与同一问题相关的博客和帖子,但所提供的解决方案都不适合我 以下是我的代码的简化: <!-- CustomItemsControl.xaml --> <ItemsControl x:Class="myNamespace.CustomItemsControl" xmlns:local="clr-namespace:myNamespace"> <ItemsControl.Resources>

标题基本上指出了这一点。我读过其他与同一问题相关的博客和帖子,但所提供的解决方案都不适合我

以下是我的代码的简化:

<!-- 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");
        }
    }
}

//CustomItemsControl.xaml.cs
名称空间myNamespace
{
公共部分类CustomItemsControl:ItemsControl
{
公共CustomItemsControl()
{
this.DefaultStyleKey=typeof(CustomItemsControl);
}
应用程序模板()上的公共重写无效
{
base.OnApplyTemplate();
var MyItemsHost=(Grid)base.GetTemplateChild(“MyItemsHost”);
}
}
}

我做错了什么?

我以前没有见过这样做,我在Generic.xaml中定义了模板,因为这是Visual Studio在执行项目->添加自定义控件(WPF)时生成的模板

您可以通过调用
InitializeComponent()使发布的代码正常工作代码。

文档中还说,您应该使用
Template.FindName(“MyItemsHost”,this)
而不是
GetTemplateChild
。如果控件可能需要网格以外的其他布局,则可能需要使用ItemsPresenter并设置ItemsPanelTemplate。

根据自定义控件的来源,您可能无法对其调用InitializeComponent()。例如,ContentControl不提供InitializeComponent

如果您检查线程,您将看到,之所以没有调用应用程序模板,是因为您将项目定义为类库,而不是自定义控件库。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)

)]

作为旁注:项目类型为“ClassLibrary”。我曾尝试在“主题”文件夹中名为“Generic.xaml”的ResourceDictionary中定义样式。我在“AssemblyInfo.cs”中也使用了“ThemeInfo”属性,但这并没有解决问题。