2013-07-24 36 views
0

我開發了自定義TreeView(稱爲MyTree)。在ResourceDictionaryGeneral.xaml這個自定義控件中,我爲TreeViewItem設置了控制模板,我需要顯示每個項目。首先,我創建特殊的控件模板:wpf:ItemsContainerStyle的設置改寫自定義TreeViewControl的所有自定義樣式

<ControlTemplate TargetType="{x:Type TreeViewItem}" x:Key="MyTreeViewItem"> 
......... 
</ControlTemplate> 

然後,我用它的自定義樣式爲MyTree

<Style TargetType="{x:Type local:MyTree}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type local:MyTree}"> 
       <ControlTemplate.Resources> 
        <Style TargetType="{x:Type TreeViewItem}"> 
         <Setter Property="Template" Value="{StaticResource MyTreeViewItem}" /> 
        </Style> 
       </ControlTemplate.Resources> 
       .......... 
       <ItemsPresenter /> 
       .......... 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

一切工作,而我用我的控制,如:

<local:MyTree> 
    <local:MyTree.ItemTemplate> 
      <HierarchicalDataTemplate ItemsSource="{Binding DependentSuites}"/> 
    </local:MyTree.ItemTemplate> 
    ..........other property specific for MyTree control............. 
</local:MyTree> 
enter code here 

而且它當我嘗試爲我的TreeViewItem添加樣式時出錯。例如,以下代碼

<local:MyTree> 
    <local:MyTree.ItemTemplate> 
      <HierarchicalDataTemplate ItemsSource="{Binding DependentSuites}"/> 
    </local:MyTree.ItemTemplate> 
    ..........other property specific for MyTree control............. 
    <local:MultiColumnTreeView.Resources> 
      <Style TargetType="TreeViewItem" 
       <Setter Property="Background" Value="Red"/> 
      </Style> 
     </local:MultiColumnTreeView.Resources> 
</local:MyTree> 

導致wpf重置我的自定義模板並開始使用TreeViewItem的默認樣式。如果我爲ItemsContainerStyle設置了任何值,那麼同樣的情況會佔用一席之地。換句話說,任何樣式修改都會在General.xaml中重寫我的自定義樣式。爲什麼會發生,以及如何避免這種情況,結合所有風格。

回答

1

您可以將其基於任何您想要的現有樣式,只修改實例所需的東西,就像使用StyleBasedOn Property一樣;

<Style TargetType="TreeViewItem" 
     BasedOn="{StaticResource YourExistingStyleYouWantToBaseItOn}"> 
    <Setter Property="Background" Value="Red"/> 
</Style> 

希望對您有所幫助。

+0

我對這個決定有些想法。但是有沒有辦法從'Themes/generic.xaml'中定義的DictionarySource中導入樣式以用於獨立CustomControls.dll中的自定義控件 – DotNetter

+0

不知道我理解這個問題,你的意思是像使用MergedDictionaries? –

+0

或者你的意思是這樣的嗎? http://stackoverflow.com/questions/338056/resourcedictionary-in-a-separate-assembly –