简体   繁体   English

HorizontalAlignment="Stretch" 在 TreeViewItem 中不起作用

[英]HorizontalAlignment="Stretch" not working in TreeViewItem

Here's an example where it is not working:这是一个不起作用的示例:

<Window x:Class="WpfApplication2.MainWindow"
        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:WpfApplication2"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <TreeView HorizontalAlignment="Stretch">
        <TreeViewItem Header="Stuff" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch">
            <Grid HorizontalAlignment="Stretch">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="auto"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Label Grid.Column="0">Some random text</Label>
                <TextBox Grid.Column="1"></TextBox>

            </Grid>
        </TreeViewItem>
    </TreeView>
</Window>

I want the text box to stretch to the width of the window, but instead you get this:我希望文本框拉伸到 window 的宽度,但您得到的是:

它看起来像什么

它在运行时的样子

The textbox expands as you type, which is not what I want.文本框会在您键入时展开,这不是我想要的。

I am thinking now it might be possible to set a binding on the width of the 2nd column to the width of the TreeViewItem but I'm not sure how to do that.我在想现在可以将第二列的宽度绑定到TreeViewItem的宽度,但我不确定该怎么做。

I've tried putting the grid in assorted panels, but that doesn't work either.我试过将网格放在各种面板中,但这也不起作用。 I have also set the HorizontalAlignment and HorizontalContentAlignment to Stretch on the textbox itself, but that also doesn't work.我还在文本框本身上将 Horizo HorizontalAlignmentHorizontalContentAlignment ntalContentAlignment 设置为Stretch ,但这也不起作用。

Is this some limitation of the Grid control?这是Grid控件的一些限制吗? Putting a textbox in a tree view by itself will make it expand as I want, but I need the label to be next to it and if there are multiple fields it looks MUCH better if all the textboxes are aligned.将文本框单独放在树视图中将使它根据需要展开,但我需要将 label 放在它旁边,如果有多个字段,如果所有文本框都对齐,它看起来会更好。

UPDATE更新

Using a different ControlTemplate allows headers to stretch but contents still don't stretch.使用不同的ControlTemplate允许标头拉伸但内容仍然不拉伸。

<TreeView HorizontalAlignment="Stretch">
        <TreeViewItem Style="{DynamicResource StretchableTreeViewItemTemplate}" HorizontalAlignment="Stretch" Header="Stuff">
            <Grid HorizontalAlignment="Stretch">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Label Grid.Column="0">Some random text</Label>
                <TextBox Grid.Column="1" HorizontalAlignment="Stretch"></TextBox>
            </Grid>
        </TreeViewItem>
    </TreeView>



<Style x:Key="StretchableTreeViewItemTemplate" TargetType="TreeViewItem"
   BasedOn="{StaticResource {x:Type TreeViewItem}}">
        <Setter Property="HorizontalContentAlignment"
      Value="Center" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TreeViewItem">
                    <StackPanel>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"
                            MinWidth="19" />
                                <ColumnDefinition Width="*" />
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto" />
                                <RowDefinition />
                            </Grid.RowDefinitions>
                            <!--
                         Note that the following do not work, but I believe the top 2 should?!
                         <ToggleButton IsChecked="{TemplateBinding IsExpanded}" ClickMode="Press" Name="Expander">
                         <ToggleButton IsChecked="{TemplateBinding Property=IsExpanded}" ClickMode="Press" Name="Expander">
                         <ToggleButton IsChecked="{TemplateBinding Path=IsExpanded}" ClickMode="Press" Name="Expander">
                    -->
                            <ToggleButton IsChecked="{Binding Path=IsExpanded, RelativeSource={RelativeSource TemplatedParent}}"
                      ClickMode="Press"
                      Name="Expander">
                                <ToggleButton.Style>
                                    <Style TargetType="ToggleButton">
                                        <Setter Property="UIElement.Focusable"
                      Value="false" />
                                        <Setter Property="FrameworkElement.Width"
                      Value="16" />
                                        <Setter Property="FrameworkElement.Height"
                      Value="16" />
                                        <Setter Property="Control.Template">
                                            <Setter.Value>
                                                <ControlTemplate TargetType="ToggleButton">
                                                    <Border Padding="5,5,5,5"
                            Background="#00FFFFFF"
                            Width="16"
                            Height="16">
                                                        <Path Fill="#00FFFFFF"
                            Stroke="#FF989898"
                            Name="ExpandPath">
                                                            <Path.Data>
                                                                <PathGeometry Figures="M0,0L0,6L6,0z" />
                                                            </Path.Data>
                                                            <Path.RenderTransform>
                                                                <RotateTransform Angle="135"
                                           CenterX="3"
                                           CenterY="3" />
                                                            </Path.RenderTransform>
                                                        </Path>
                                                    </Border>
                                                    <ControlTemplate.Triggers>
                                                        <Trigger Property="UIElement.IsMouseOver"
                               Value="True">
                                                            <Setter TargetName="ExpandPath"
                                Property="Shape.Stroke"
                                Value="#FF1BBBFA" />
                                                            <Setter TargetName="ExpandPath"
                                Property="Shape.Fill"
                                Value="#00FFFFFF" />
                                                        </Trigger>
                                                        <Trigger Property="ToggleButton.IsChecked"
                               Value="True">
                                                            <Setter TargetName="ExpandPath"
                                Property="UIElement.RenderTransform">
                                                                <Setter.Value>
                                                                    <RotateTransform Angle="180"
                                             CenterX="3"
                                             CenterY="3" />
                                                                </Setter.Value>
                                                            </Setter>
                                                            <Setter TargetName="ExpandPath"
                                Property="Shape.Fill"
                                Value="#FF595959" />
                                                            <Setter TargetName="ExpandPath"
                                Property="Shape.Stroke"
                                Value="#FF262626" />
                                                        </Trigger>
                                                    </ControlTemplate.Triggers>
                                                </ControlTemplate>
                                            </Setter.Value>
                                        </Setter>
                                    </Style>
                                </ToggleButton.Style>
                            </ToggleButton>
                            <Border x:Name="Bd"
                HorizontalAlignment="Stretch"
                BorderThickness="{TemplateBinding Border.BorderThickness}"
                BorderBrush="{TemplateBinding Border.BorderBrush}"
                Padding="{TemplateBinding Control.Padding}"
                Background="{TemplateBinding Panel.Background}"
                SnapsToDevicePixels="True"
                Grid.Column="1">
                                <ContentPresenter x:Name="PART_Header"
                            Content="{TemplateBinding HeaderedContentControl.Header}"
                            ContentTemplate="{TemplateBinding HeaderedContentControl.HeaderTemplate}"
                            ContentStringFormat="{TemplateBinding HeaderedItemsControl.HeaderStringFormat}"
                            ContentTemplateSelector="{TemplateBinding HeaderedItemsControl.HeaderTemplateSelector}"
                            ContentSource="Header"
                            HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
                            SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
                            </Border>
                            <ItemsPresenter x:Name="ItemsHost"
                        Grid.Column="1"
                        Grid.Row="1" />
                        </Grid>
                    </StackPanel>
                    <ControlTemplate.Triggers>
                        <Trigger Property="TreeViewItem.IsExpanded"
               Value="False">
                            <Setter TargetName="ItemsHost"
                Property="UIElement.Visibility"
                Value="Collapsed" />
                        </Trigger>
                        <Trigger Property="ItemsControl.HasItems"
               Value="False">
                            <Setter TargetName="Expander"
                Property="UIElement.Visibility"
                Value="Hidden" />
                        </Trigger>
                        <Trigger Property="TreeViewItem.IsSelected"
               Value="True">
                            <Setter TargetName="Bd"
                Property="Panel.Background"
                Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}" />
                            <Setter Property="TextElement.Foreground"
                Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}" />
                        </Trigger>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="TreeViewItem.IsSelected"
                     Value="True" />
                                <Condition Property="Selector.IsSelectionActive"
                     Value="False" />
                            </MultiTrigger.Conditions>
                            <Setter TargetName="Bd"
                Property="Panel.Background"
                Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />
                            <Setter Property="TextElement.Foreground"
                Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
                        </MultiTrigger>
                        <Trigger Property="UIElement.IsEnabled"
               Value="False">
                            <Setter Property="TextElement.Foreground"
                Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Results:结果:

编辑了控制模板

Trying with Pikoh's solution:尝试使用 Pikoh 的解决方案:

<local:StretchingTreeView HorizontalAlignment="Stretch">
    <local:StretchingTreeViewItem HorizontalAlignment="Stretch" Header="Stuff">
        <Grid HorizontalAlignment="Stretch">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Label Grid.Column="0">Some random text</Label>
            <TextBox Grid.Column="1" HorizontalAlignment="Stretch"></TextBox>
        </Grid>
    </local:StretchingTreeViewItem>
</local:StretchingTreeView>

Pikoh 解决方案的结果

Try something like this:尝试这样的事情:

<TextBox Grid.Column="1" Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource AncestorType={x:Type Grid}}, Mode=OneWay}"></TextBox>

Edit编辑

Ok,i've found one solution Here .好的,我在这里找到了一种解决方案。 It basically creates a new class inheriting Treeview:它基本上创建了一个继承 Treeview 的新类:

class StretchingTreeView : TreeView
{
    protected override DependencyObject GetContainerForItemOverride()
    {
        return new StretchingTreeViewItem();
    }

    protected override bool IsItemItsOwnContainerOverride(object item)
    {
        return item is StretchingTreeViewItem;
    }
}

class StretchingTreeViewItem : TreeViewItem
{
    public StretchingTreeViewItem()
    {
        this.Loaded += new RoutedEventHandler(StretchingTreeViewItem_Loaded);
    }

    private void StretchingTreeViewItem_Loaded(object sender, RoutedEventArgs e)
    {
        // The purpose of this code is to stretch the Header Content all the way accross the TreeView. 
        if (this.VisualChildrenCount > 0)
        {
            Grid grid = this.GetVisualChild(0) as Grid;
            if (grid != null && grid.ColumnDefinitions.Count == 3)
            {
                // Remove the middle column which is set to Auto and let it get replaced with the 
                // last column that is set to Star.
                grid.ColumnDefinitions.RemoveAt(1);
            }
        }
    }

    protected override DependencyObject GetContainerForItemOverride()
    {
        return new StretchingTreeViewItem();
    }

    protected override bool IsItemItsOwnContainerOverride(object item)
    {
        return item is StretchingTreeViewItem;
    }
}

Example usage:用法示例:

<Window x:Class="WpfApplication2.Window2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication2"
    Title="Window2" Height="300" Width="300">
<Grid>

    <local:StretchingTreeView HorizontalAlignment="Stretch" >

        <local:StretchingTreeViewItem Header="Stuff" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" >
            <Grid HorizontalAlignment="Stretch" >
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="auto"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Label Grid.Column="0">Some random text</Label>
                <TextBox Grid.Column="1" ></TextBox>

            </Grid>
        </local:StretchingTreeViewItem>
    </local:StretchingTreeView>
</Grid>

Due to an odd design decision by Microsoft when creating WPF, tree items can't stretch without replacing the control template.由于 Microsoft 在创建 WPF 时做出的一个奇怪的设计决定,如果不替换控件模板就无法拉伸树项。

See http://leecampbell.blogspot.com/2009/01/horizontal-stretch-on-treeviewitems.htmlhttp://leecampbell.blogspot.com/2009/01/horizo​​ntal-stretch-on-treeviewitems.html

The required style is:需要的样式是:

<Style TargetType="TreeViewItem"
       BasedOn="{StaticResource {x:Type TreeViewItem}}">
  <Setter Property="HorizontalContentAlignment"
          Value="Center" />
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="TreeViewItem">
        <StackPanel>
          <Grid>
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="Auto"
                                MinWidth="19" />
              <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
              <RowDefinition Height="Auto" />
              <RowDefinition />
            </Grid.RowDefinitions>
            <!--
                             Note that the following do not work, but I believe the top 2 should?!
                             <ToggleButton IsChecked="{TemplateBinding IsExpanded}" ClickMode="Press" Name="Expander">
                             <ToggleButton IsChecked="{TemplateBinding Property=IsExpanded}" ClickMode="Press" Name="Expander">
                             <ToggleButton IsChecked="{TemplateBinding Path=IsExpanded}" ClickMode="Press" Name="Expander">
                        -->
            <ToggleButton IsChecked="{Binding Path=IsExpanded, RelativeSource={RelativeSource TemplatedParent}}"
                          ClickMode="Press"
                          Name="Expander">
              <ToggleButton.Style>
                <Style TargetType="ToggleButton">
                  <Setter Property="UIElement.Focusable"
                          Value="false" />
                  <Setter Property="FrameworkElement.Width"
                          Value="16" />
                  <Setter Property="FrameworkElement.Height"
                          Value="16" />
                  <Setter Property="Control.Template">
                    <Setter.Value>
                      <ControlTemplate TargetType="ToggleButton">
                        <Border Padding="5,5,5,5"
                                Background="#00FFFFFF"
                                Width="16"
                                Height="16">
                          <Path Fill="#00FFFFFF"
                                Stroke="#FF989898"
                                Name="ExpandPath">
                            <Path.Data>
                              <PathGeometry Figures="M0,0L0,6L6,0z" />
                            </Path.Data>
                            <Path.RenderTransform>
                              <RotateTransform Angle="135"
                                               CenterX="3"
                                               CenterY="3" />
                            </Path.RenderTransform>
                          </Path>
                        </Border>
                        <ControlTemplate.Triggers>
                          <Trigger Property="UIElement.IsMouseOver"
                                   Value="True">
                            <Setter TargetName="ExpandPath"
                                    Property="Shape.Stroke"
                                    Value="#FF1BBBFA" />
                            <Setter TargetName="ExpandPath"
                                    Property="Shape.Fill"
                                    Value="#00FFFFFF" />
                          </Trigger>
                          <Trigger Property="ToggleButton.IsChecked"
                                   Value="True">
                            <Setter TargetName="ExpandPath"
                                    Property="UIElement.RenderTransform">
                              <Setter.Value>
                                <RotateTransform Angle="180"
                                                 CenterX="3"
                                                 CenterY="3" />
                              </Setter.Value>
                            </Setter>
                            <Setter TargetName="ExpandPath"
                                    Property="Shape.Fill"
                                    Value="#FF595959" />
                            <Setter TargetName="ExpandPath"
                                    Property="Shape.Stroke"
                                    Value="#FF262626" />
                          </Trigger>
                        </ControlTemplate.Triggers>
                      </ControlTemplate>
                    </Setter.Value>
                  </Setter>
                </Style>
              </ToggleButton.Style>
            </ToggleButton>
            <Border x:Name="Bd"
                    HorizontalAlignment="Stretch"
                    BorderThickness="{TemplateBinding Border.BorderThickness}"
                    BorderBrush="{TemplateBinding Border.BorderBrush}"
                    Padding="{TemplateBinding Control.Padding}"
                    Background="{TemplateBinding Panel.Background}"
                    SnapsToDevicePixels="True"
                    Grid.Column="1">
              <ContentPresenter x:Name="PART_Header"
                                Content="{TemplateBinding HeaderedContentControl.Header}"
                                ContentTemplate="{TemplateBinding HeaderedContentControl.HeaderTemplate}"
                                ContentStringFormat="{TemplateBinding HeaderedItemsControl.HeaderStringFormat}"
                                ContentTemplateSelector="{TemplateBinding HeaderedItemsControl.HeaderTemplateSelector}"
                                ContentSource="Header"
                                HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
                                SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
            </Border>
            <ItemsPresenter x:Name="ItemsHost"
                            Grid.Column="1"
                            Grid.Row="1" />
          </Grid>
        </StackPanel>
        <ControlTemplate.Triggers>
          <Trigger Property="TreeViewItem.IsExpanded"
                   Value="False">
            <Setter TargetName="ItemsHost"
                    Property="UIElement.Visibility"
                    Value="Collapsed" />
          </Trigger>
          <Trigger Property="ItemsControl.HasItems"
                   Value="False">
            <Setter TargetName="Expander"
                    Property="UIElement.Visibility"
                    Value="Hidden" />
          </Trigger>
          <Trigger Property="TreeViewItem.IsSelected"
                   Value="True">
            <Setter TargetName="Bd"
                    Property="Panel.Background"
                    Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}" />
            <Setter Property="TextElement.Foreground"
                    Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}" />
          </Trigger>
          <MultiTrigger>
            <MultiTrigger.Conditions>
              <Condition Property="TreeViewItem.IsSelected"
                         Value="True" />
              <Condition Property="Selector.IsSelectionActive"
                         Value="False" />
            </MultiTrigger.Conditions>
            <Setter TargetName="Bd"
                    Property="Panel.Background"
                    Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />
            <Setter Property="TextElement.Foreground"
                    Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
          </MultiTrigger>
          <Trigger Property="UIElement.IsEnabled"
                   Value="False">
            <Setter Property="TextElement.Foreground"
                    Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

It seems like Grid's HorizontalAlignment Issue.似乎是Grid's HorizontalAlignment问题。 I've tried it in .我在 . Net Framework 4 and it all works fine. Net Framework 4,一切正常。 Seems like in 4.5 even though you specify HorizontalAlignment as Stretch , it actually doesn't stretch it.似乎在 4.5 中,即使您将HorizontalAlignment指定为Stretch ,它实际上也不会拉伸它。 So you can do a binding like below:因此,您可以进行如下绑定:

<Grid HorizontalAlignment="Stretch" 
      Width="{Binding RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}},Path=ActualWidth,Mode=OneTime}"
              >

Cause you can see in the run time that TreeViewItem has Width expected but Grid doesn't.因为您可以在运行时看到 TreeViewItem 具有 Width 预期但 Grid 没有。

The core of the issue (and the way to fix it) is described here :这个问题(并修复它的方式)的核心是描述在这里

The default ControlTemplate for the TreeViewItem uses a grid of 3 columns x 2 rows, defined such that the content cannot stretch horizontally. TreeViewItem的默认ControlTemplate使用 3 列 x 2 行的网格,定义为内容不能水平拉伸。 The author also gives a modified style, that changes the grid so that the content can stretch.作者还提供了一种修改样式,即更改网格以便内容可以拉伸。

Note that the modified style sets the HorizontalContentAlignment of TreeViewItem to Center , and that the ControlTemplate uses this property for aligning the content.请注意,修改后的样式将TreeViewItemHorizontalContentAlignment设置为Center ,并且ControlTemplate使用此属性来对齐内容。

To achieve the desired effect, either set HorizontalContentAlignment to Stretch in the modified style, or override just that property on the TreeView (or specific TreeViewItems ).要获得所需的效果,请在修改后的样式中将HorizontalContentAlignment设置为Stretch ,或者覆盖TreeView (或特定TreeViewItems )上的该属性

Missing the BasedOn="{StaticResource {x:Type TreeViewItem}}" part causes the TreeViewItem to revert to using the default ControlTemplate , with the non-stretchable grid.缺少BasedOn="{StaticResource {x:Type TreeViewItem}}"部分会导致 TreeViewItem 恢复到使用默认ControlTemplate和不可拉伸网格。

<Style TargetType="TreeViewItem" BasedOn="{StaticResource {x:Type TreeViewItem}}">
    <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>

In a HierarchicalDataTemplate , the effect would be achieved by using the ItemContainerStyle property.HierarchicalDataTemplate ,效果将通过使用ItemContainerStyle属性来实现。

@pikoh's method of deriving from TreeView and TreeViewItem achieves the same, by modifying the grid from code. @pikoh 的从TreeViewTreeViewItem派生的方法通过修改代码中的网格来实现相同的目的。

Complete example:完整示例:

<Window x:Class="WpfApp1.MainWindow"
        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:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <Style TargetType="TreeViewItem" BasedOn="{StaticResource {x:Type TreeViewItem}}">
            <Setter Property="HorizontalContentAlignment" Value="Center" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="TreeViewItem">
                        <StackPanel>
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="Auto"
                                MinWidth="19" />
                                    <ColumnDefinition Width="*" />
                                </Grid.ColumnDefinitions>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto" />
                                    <RowDefinition />
                                </Grid.RowDefinitions>
                                <!-- Note that the following do not work, but I believe the top 2 should?! -->
                                <ToggleButton IsChecked="{Binding Path=IsExpanded, RelativeSource={RelativeSource TemplatedParent}}" ClickMode="Press" Name="Expander">
                                    <ToggleButton.Style>
                                        <Style TargetType="ToggleButton">
                                            <Setter Property="UIElement.Focusable" Value="false" />
                                            <Setter Property="FrameworkElement.Width" Value="16" />
                                            <Setter Property="FrameworkElement.Height" Value="16" />
                                            <Setter Property="Control.Template">
                                                <Setter.Value>
                                                    <ControlTemplate TargetType="ToggleButton">
                                                        <Border Padding="5,5,5,5" Background="#00FFFFFF" Width="16" Height="16">
                                                            <Path Fill="#00FFFFFF" Stroke="#FF989898" Name="ExpandPath">
                                                                <Path.Data>
                                                                    <PathGeometry Figures="M0,0L0,6L6,0z" />
                                                                </Path.Data>
                                                                <Path.RenderTransform>
                                                                    <RotateTransform Angle="135" CenterX="3" CenterY="3" />
                                                                </Path.RenderTransform>
                                                            </Path>
                                                        </Border>
                                                        <ControlTemplate.Triggers>
                                                            <Trigger Property="UIElement.IsMouseOver" Value="True">
                                                                <Setter TargetName="ExpandPath" Property="Shape.Stroke" Value="#FF1BBBFA" />
                                                                <Setter TargetName="ExpandPath" Property="Shape.Fill" Value="#00FFFFFF" />
                                                            </Trigger>
                                                            <Trigger Property="ToggleButton.IsChecked" Value="True">
                                                                <Setter TargetName="ExpandPath" Property="UIElement.RenderTransform">
                                                                    <Setter.Value>
                                                                        <RotateTransform Angle="180" CenterX="3" CenterY="3" />
                                                                    </Setter.Value>
                                                                </Setter>
                                                                <Setter TargetName="ExpandPath" Property="Shape.Fill" Value="#FF595959" />
                                                                <Setter TargetName="ExpandPath" Property="Shape.Stroke" Value="#FF262626" />
                                                            </Trigger>
                                                        </ControlTemplate.Triggers>
                                                    </ControlTemplate>
                                                </Setter.Value>
                                            </Setter>
                                        </Style>
                                    </ToggleButton.Style>
                                </ToggleButton>
                                <Border x:Name="Bd"
                    HorizontalAlignment="Stretch"
                    BorderThickness="{TemplateBinding Border.BorderThickness}"
                    BorderBrush="{TemplateBinding Border.BorderBrush}"
                    Padding="{TemplateBinding Control.Padding}"
                    Background="{TemplateBinding Panel.Background}"
                    SnapsToDevicePixels="True"
                    Grid.Column="1">
                                    <ContentPresenter x:Name="PART_Header"
                                Content="{TemplateBinding HeaderedContentControl.Header}"
                                ContentTemplate="{TemplateBinding HeaderedContentControl.HeaderTemplate}"
                                ContentStringFormat="{TemplateBinding HeaderedItemsControl.HeaderStringFormat}"
                                ContentTemplateSelector="{TemplateBinding HeaderedItemsControl.HeaderTemplateSelector}"
                                ContentSource="Header"
                                HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
                                SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
                                </Border>
                                <ItemsPresenter x:Name="ItemsHost" Grid.Column="1" Grid.Row="1" />
                            </Grid>
                        </StackPanel>
                        <ControlTemplate.Triggers>
                            <Trigger Property="TreeViewItem.IsExpanded" Value="False">
                                <Setter TargetName="ItemsHost" Property="UIElement.Visibility" Value="Collapsed" />
                            </Trigger>
                            <Trigger Property="ItemsControl.HasItems" Value="False">
                                <Setter TargetName="Expander" Property="UIElement.Visibility" Value="Hidden" />
                            </Trigger>
                            <Trigger Property="TreeViewItem.IsSelected" Value="True">
                                <Setter TargetName="Bd" Property="Panel.Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}" />
                                <Setter Property="TextElement.Foreground"  Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}" />
                            </Trigger>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="TreeViewItem.IsSelected" Value="True" />
                                    <Condition Property="Selector.IsSelectionActive" Value="False" />
                                </MultiTrigger.Conditions>
                                <Setter TargetName="Bd"  Property="Panel.Background"  Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />
                                <Setter Property="TextElement.Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
                            </MultiTrigger>
                            <Trigger Property="UIElement.IsEnabled" Value="False">
                                <Setter Property="TextElement.Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <TreeView HorizontalAlignment="Stretch">
        <TreeView.Resources>
            <Style TargetType="TreeViewItem" BasedOn="{StaticResource {x:Type TreeViewItem}}">
                <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
            </Style>
        </TreeView.Resources>
        <TreeViewItem Header="Stuff" HorizontalAlignment="Stretch">
            <Grid HorizontalAlignment="Stretch">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="auto"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Label Grid.Column="0">Some random text</Label>
                <TextBox Grid.Column="1"></TextBox>
            </Grid>
        </TreeViewItem>
    </TreeView>
</Window>

屏幕截图

All you need to do is add Grid.ColumnSpan='2' to the ControlTemplate of the TreeViewItem as shown below.您需要做的就是将Grid.ColumnSpan='2'添加到TreeViewItemControlTemplate中,如下所示。

在此处输入图像描述

Thats it!就是这样!

Explanation: The default ControlTemplate places the Header Content in a Grid column that does not stretch.解释:默认的ControlTemplate将 Header Content 放在一个不拉伸的 Grid 列中。 The Grid.ColumnSpan='2' instructs the Header content to span to the rest of the Grid. Grid.ColumnSpan='2'指示 Header 内容跨越到 Grid 的 rest。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 wpf 水平对齐左和拉伸? - wpf horizontalalignment left and stretch? UWP TreeViewItem 水平拉伸 - UWP TreeViewItem Horizontal Stretch UWP ItemsStackPanel在ListView内拉伸Horizo​​ntalAlignment - UWP ItemsStackPanel stretch HorizontalAlignment inside a ListView 设置&#39;Horizo​​ntalAlignment =“ Stretch”&#39;时,如何获取&#39;Width&#39;? - How to get the 'Width', when set 'HorizontalAlignment = “Stretch”'? Horizo​​ntalAlignment在DataGridTextColumn中的ComboBox上不起作用 - HorizontalAlignment not working on ComboBox in DataGridTextColumn 图像上的Horizo​​ntalAlignment在itextsharp中的PdfPCell中不起作用 - HorizontalAlignment on image not working in PdfPCell in itextsharp 如何使用“XAML Toolkit中的Material Design”控件拉伸TreeViewItem - How to stretch TreeViewItem using “Material Design In XAML Toolkit” controls 当 Horizo​​ntalAlignment 和 Horizo​​ntalContentAlignment 不起作用时,如何使 WPF 中的控件拉伸以填充可用宽度? - How can I make controls in WPF stretch to fill available width when HorizontalAlignment and HorizontalContentAlignment don't work? 如何使 DataGrid 列水平对齐拉伸和自定义列名称 - UWP DataGrid - How to make DataGrid columns horizontalalignment stretch & customize column name - UWP DataGrid 水平对齐问题 - HorizontalAlignment Issue
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM