wpf TreeViewItem 中的背景不是全宽

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16374182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:43:41  来源:igfitidea点击:

Background in TreeViewItem not full width

c#wpfxaml

提问by gankstaman the first

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

我是 WPF 表单的新手,在尝试在 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.

问题是在 StackPanel 中设置的背景没有达到 TreeView 控件的全宽(向右)。我尝试HorizontalAllignment="Stretch"从 TreeView 向下添加所有控件,但没有效果。StackPanel 上的背景宽度仅到 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.

通过在 TreeView 上设置背景,我确认它确实占据了表单的整个宽度,因此这不是问题。

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

有谁知道如何将背景扩展到 TreeView 大小的末尾?

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

我将如何以最简单的方式覆盖这个网格?

回答by jure

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

这是一篇涵盖问题并提供解决方案的博客文章。据我所知,它对我有用。基本上你需要重新设计 TreeViewItem。很多 Xaml 但我认为是唯一合适的解决方案

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

https://leecampbell.com/2009/01/14/horizo​​ntal-stretch-on-treeviewitems/

回答by Neophyte

This is just to extend this old post with some visuals.

这只是为了用一些视觉效果扩展这篇旧帖子。

Issue statement: cannot right-align content in TreeView by default -based on some other comments here&there - I tested to remove any stackpanels from the Xaml (yet it is not the issue as I can replicate the desired design outside of TreeView with stackpanels)

问题声明:默认情况下无法右对齐 TreeView 中的内容 - 基于此处和那里的其他一些评论 - 我测试从 Xaml 中删除任何堆栈面板(但这不是问题,因为我可以使用堆栈面板在 TreeView 之外复制所需的设计)

TLDR: Workarounds are posted in previous comments

TLDR:变通方法已在之前的评论中发布

The XAML:

XAML:

<Window x:Class="Test"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:DbSeeder.WPF.View"
    mc:Ignorable="d"
    Title="Test" 
    Height="450" 
    Width="800"
    Loaded="Window_Loaded">
<DockPanel>
    <!-- what i want -->
    <StackPanel DockPanel.Dock="Top"
                Margin="5">
        <Label Content="This is the expected structure" 
               FontFamily="Verdana"
               FontWeight="Bold"
               BorderBrush="Black"
               BorderThickness="2"
               HorizontalAlignment="Stretch"
               Background="Orange"
               />
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="5*"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <!-- Buttons -->
            <StackPanel Grid.Column="1" 
                        Orientation="Horizontal" 
                        HorizontalAlignment="Right"
                        Margin="3">
                <Button Content="Button 1"
                        Margin="5"/>
                <Button Content="Button 2"
                        Margin="3"/>
            </StackPanel>

            <!-- Keys -->
            <StackPanel Grid.Column="0"
                        Orientation="Horizontal"
                        HorizontalAlignment="Left"
                        Margin="3" >
                <Label Content="Here should come key 1" Margin="3" BorderBrush="Black" BorderThickness="2"/>
                <Label Content="Here should come key 2" Margin="3" BorderBrush="Black" BorderThickness="2"/>
            </StackPanel>
        </Grid>
    </StackPanel>

    <!-- What I get 2-->
    <Grid 
        ShowGridLines="True"
        DockPanel.Dock="Top"
        Margin="5">

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <Label Content="This is what I get" 
               FontFamily="Verdana"
               FontWeight="Bold"
               BorderBrush="Black"
               BorderThickness="2"
               Background="Orange"
               Grid.Column="0"
               Grid.Row="0"/>
        <TreeView x:Name="alternative2"
                  Grid.Column="0"
                  Grid.Row="1"
                  HorizontalContentAlignment="Stretch"
                  HorizontalAlignment="Stretch">
            <TreeView.Resources>
                <Style TargetType="{x:Type TreeViewItem}">
                    <Setter Property="HeaderTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                    <Grid ShowGridLines="True"
                                          DockPanel.Dock="Top"
                                          Margin="5">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="3*"/>
                                            <ColumnDefinition Width="3*"/>
                                            <ColumnDefinition Width="*"/>
                                            <ColumnDefinition Width="*"/>
                                        </Grid.ColumnDefinitions>
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="Auto"/>
                                        </Grid.RowDefinitions>

                                        <!-- Buttons -->
                                        <Button Content="Button 1"
                                                Grid.Column="2" 
                                                Margin="5"
                                                HorizontalAlignment="Stretch"/>
                                        <Button Content="Button 2"
                                                Grid.Column="3" 
                                                Margin="3"
                                                HorizontalAlignment="Stretch"/>

                                        <!-- Keys -->

                                        <Label Grid.Column="0" 
                                               HorizontalAlignment="Stretch" 
                                               Content="Here should come key 1" 
                                               Margin="3" 
                                               BorderBrush="Black" 
                                               BorderThickness="2"/>
                                        <Label Grid.Column="1"
                                               HorizontalAlignment="Stretch" 
                                               Content="Here should come key 2" 
                                               Margin="3" 
                                               BorderBrush="Black" 
                                               BorderThickness="2"/>
                                    </Grid>
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </TreeView.Resources>
        </TreeView>
    </Grid>
</DockPanel>

And the code behind (to seed the view)

以及背后的代码(以播种视图)

public partial class Test : Window
{
    protected IDictionary<string, object> JsonFields { get; set; }

    public Test()
    {
        InitializeComponent();
        var x = new Dictionary<string, string>()
        {
            {"key 1", "string" },
            {"key 2", "string 2" }
        };

        var y = new List<string>()
        {
            "subList5a",
            "subList5b",
        };

        JsonFields = new Dictionary<string, object>()
        {
            { "Key 1", "string" },
            { "Key 2", "string" },
            { "Key 3", "string" },
            { "Key 4 - dict", x },
            { "Key 5 - List", y }
        };
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        var counter = 0;
        foreach (var key in JsonFields.Keys)
        {
            counter++;

            var item = new TreeViewItem()
            {
                Header = key,
                ClipToBounds = true
            };

            if (counter % 2 == 0)
            {
                var subItem = new TreeViewItem()
                {
                    Header = $"SubKey of {item.Header}",
                    ClipToBounds = true
                };

                item.Items.Add(subItem);
            }
            alternative2.Items.Add(item);
        }
    }
}

Issue example

问题示例