Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background in TreeViewItem not full width

Tags:

c#

wpf

xaml

I am new to WPF forms and I ran across an issue when trying to set a background in a TreeViewItem.

<Window x:Class="wpf_test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <!--Styles-->
        <Style x:Key="GUIEntity" TargetType="{x:Type Control}">
            <Setter Property="MinWidth" Value="150" />
            <Setter Property="MaxWidth" Value="150" />
        </Style>
        <Style TargetType="TreeViewItem">
            <Setter Property="IsExpanded" Value="True" />
        </Style>
        <!--Data Sources-->
        <x:Array x:Key="BooleanListData" Type="sys:String" xmlns:sys="clr-namespace:System;assembly=mscorlib">
            <sys:String>True</sys:String>
            <sys:String>False</sys:String>
        </x:Array>
    </Window.Resources>
    <Grid>
        <TreeView Name="treeView1" Margin="5" Background="Azure">
            <TreeViewItem Header="ComplexTypeProperty" Margin="5">
                <CheckBox Style="{StaticResource GUIEntity}" Margin="3,3,10,3" Content="Instance" />
                <StackPanel Orientation="Horizontal" Background="LightGray">
                    <Label Margin="0,2,0,0" Content="IsBoolProperty" Width="150" />
                    <ComboBox Margin="5" Style="{StaticResource GUIEntity}" ItemsSource="{StaticResource BooleanListData}" />
                </StackPanel>
            </TreeViewItem>
        </TreeView>
    </Grid>
</Window>

The problem is that the background being set in the StackPanel doesn't go the full width (to the right) of the TreeView control. I tried adding HorizontalAllignment="Stretch" to all the controls from the TreeView down but it had no effect. The width of the background on the StackPanel goes only to the end of the ComboBox.

By setting a background on the TreeView I confirmed that it did take up the full width of the form so that wouldn't be the issue.

Does anyone know how to extend the background to the end of the TreeView's size?

How would i go about overriding this grid in the simplest way?

like image 779
gankstaman the first Avatar asked Nov 30 '25 08:11

gankstaman the first


1 Answers

Here is a blog post that covers problem and gives a solution. As far as I remember, it worked ok for me. Basically you need to retemplate TreeViewItem. Lot of Xaml but I think is the only proper solution

https://leecampbell.com/2009/01/14/horizontal-stretch-on-treeviewitems/

like image 195
Jurica Smircic Avatar answered Dec 02 '25 00:12

Jurica Smircic