2011-06-04 34 views
1

标题基本上指出了它。我已阅读与同一问题相关的其他博客和帖子,但没有提供的解决方案为我工作。WPF OnApplyTemplate对ItemsControl的派生类不叫

这里是我的代码的简化:

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

我做错了吗?

+0

补充说明:项目类型为“ClassLibrary”。我试图在ResourceDictionary中的“Themes”文件夹中定义一个名为“Generic.xaml”的样式。我也在我的“AssemblyInfo.cs”中使用了“ThemeInfo”属性,但都没有解决问题。 – 0xbadf00d 2011-06-04 17:54:15

回答

1

我还没有看到它以前完成,我定义了Generic.xaml中的模板,因为这是Visual Studio生成时,你去项目 - >添加自定义控件(WPF)。

你可以通过在你的构造函数中调用InitializeComponent();来使你发布的代码工作。 此外,文档说您应该使用Template.FindName("MyItemsHost",this)而不是GetTemplateChild。如果您的控件可能需要与网格不同的布局,则可能需要使用ItemsPresenter并设置ItemsPanelTemplate。

1

根据您的自定义控件派生自的内容,您可能无法在其上调用InitializeComponent()。例如,ContentControl不提供InitializeComponent。

如果您检查this线程,您会发现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)