2009-11-04 104 views
2

在WPF中,我有一個從TreeView繼承的自定義控件。代碼如下...在WPF中,爲什麼我的Generic.xaml中的樣式未應用於我的自定義控件?

public class CustomTRV : TreeView 
{ 
    static CustomTRV() 
    { 
     //Removed this because I want the default TreeView look. 
     //......CustomTRV.DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomTRV), new FrameworkPropertyMetadata(typeof(CustomTRV))); 
    } 

    public void Connect(string entityHierarchyToken) 
    { 
     //build viewModel classes... 
     this.ItemsSource = new List<ViewModel>() 
     { 
      new ViewModel() { TextValue = "aaaa" }, 
      new ViewModel() { TextValue = "bbb" }, 
      new ViewModel() { TextValue = "ccc" }, 
      new ViewModel() { TextValue = "ddd" }, 
      new ViewModel() { TextValue = "eee" }, 
     }; 
    } 
} 

在Generic.xaml內容如下所示...

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:WpfTestCustomControl"> 

    <HierarchicalDataTemplate DataType="{x:Type local:ViewModel}"> 
     <TextBlock Foreground="Blue" Text="{Binding Path=TextValue}"></TextBlock> 
    </HierarchicalDataTemplate> 

    <Style TargetType="{x:Type local:CustomTRV}"> 
     <Setter Property="ItemContainerStyle"> 
      <Setter.Value> 

       <Style TargetType="{x:Type TreeViewItem}"> 
        <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" /> 
        <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" /> 
        <Setter Property="FontWeight" Value="Bold" /> 
        <Style.Triggers> 
         <Trigger Property="IsSelected" Value="True"> 
          <Setter Property="FontWeight" Value="Normal" /> 
         </Trigger> 
        </Style.Triggers> 
       </Style> 

      </Setter.Value> 
     </Setter> 
    </Style> 
</ResourceDictionary> 

我認爲Generic.xaml代碼應該得到應用到我的控制,並作爲這樣的ItemContainer屬性值應該被設置。但它看起來像ItemContainerStyle沒有任何影響。

注意:Generic.xaml的HierarchicalDataTemplate確實工作正常,所以文件正在被解釋。

任何想法?

+0

如果你正在做MVVM,你會混淆你的Models和ViewModels。 – Will 2009-11-04 13:02:16

+0

我「認爲」我正在做普通的ViewModel,根據這個CodeProject文章 - http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx 因此,'視圖模型'可能是一個令人困惑的名稱爲我的數據類。它應該是像'MyDataObjectToDisplay'。 – willem 2009-11-04 13:10:36

回答

3

MVVM的問題與自定義控件不談,問題是你已經註釋掉的樣式與您的自定義控制相關聯行:

//CustomTRV.DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomTRV), new FrameworkPropertyMetadata(typeof(CustomTRV))); 

人體工程學,你的控制只會有標準樣式TreeView秒。

+0

這有關係嗎?因爲我只是覆蓋ItemContainerStyle,而不是模板? – willem 2009-11-04 14:22:21

+0

是的,因爲ItemContainerStyle包含在適用於CustomTRV的Style中。 CustomTRV的風格永遠不會被應用,因爲它沒有與CustomTRV類相關聯。嘗試取消註釋該行。 – 2009-11-04 14:53:14

+1

太棒了。這就是訣竅。我掙扎了一下,因爲我必須確保我的樣式基於普通的TreeView樣式。除此之外,您的建議還做了一些小技巧: