In WPF, why does my Style in Generic.xaml not get applied to my Custom Control?

3.6k views Asked by At

In WPF, I have a custom control that inherits from TreeView. The code is as follows...

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" },
        };
    }
}

The content in Generic.xaml looks as follows...

<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>

I thought the Generic.xaml code should get applied to my control, and as such the ItemContainer property value should be set. But it looks like the ItemContainerStyle does not have any effect whatsoever.

NOTE: the HierarchicalDataTemplate from Generic.xaml DOES work ok, so the file is being interpreted.

Any ideas?

1

There are 1 answers

3
Kent Boogaart On BEST ANSWER

Questions of MVVM versus custom control aside, the problem is you've commented out the line that associates the style with your custom control:

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

Ergo, your control will just have the standard style for TreeViews.