2011-06-04 65 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)