2009-11-04 20 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样式。除此之外,您的建议还做了一些小技巧: