be_mi
be_mi

Reputation: 569

WPF TreeView "autowidth" over several items?

What is the right way to display columns in a tree view, that auto align their width to the width of the content. The problem that I see is, that each TreeViewItem is independent and therefor I don't know how to tell that eg the date column in every TreeViewItem shall have the same width, but depending on the TreeViewItem with the widest date string?

  <TreeView Name="treeView" TreeViewItem.Expanded="TreeViewItem_Expanded" AutomationProperties.IsColumnHeader="True" AutomationProperties.IsRowHeader="True" AllowDrop="True" VirtualizingStackPanel.IsVirtualizing="True" VirtualizingStackPanel.VirtualizationMode="Recycling">

    <TreeViewItem>
      <TreeViewItem.Header>
        <Grid>
          <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="auto" />
          </Grid.ColumnDefinitions>
          <Label>2.3.00</Label>
          <Label Grid.Column="2">Something</Label>
        </Grid>
      </TreeViewItem.Header>
    </TreeViewItem>

    <TreeViewItem>
      <TreeViewItem.Header>
        <Grid>
          <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="auto" />
          </Grid.ColumnDefinitions>
          <Label>22.03.2000</Label>
          <Label Grid.Column="2">Something 2</Label>
        </Grid>
      </TreeViewItem.Header>
    </TreeViewItem>
  </TreeView>

Upvotes: 0

Views: 962

Answers (1)

Flat Eric
Flat Eric

Reputation: 8111

Use a SharedSizeGroup

<TreeView Name="treeView" Grid.IsSharedSizeScope="True" TreeViewItem.Expanded="TreeViewItem_Expanded" AutomationProperties.IsColumnHeader="True" AutomationProperties.IsRowHeader="True" AllowDrop="True" VirtualizingStackPanel.IsVirtualizing="True" VirtualizingStackPanel.VirtualizationMode="Recycling">

  <TreeViewItem>
    <TreeViewItem.Header>
      <Grid>
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="*" SharedSizeGroup="A" />
          <ColumnDefinition Width="auto" SharedSizeGroup="B"  />
        </Grid.ColumnDefinitions>
        <Label>2.3.00</Label>
        <Label Grid.Column="2">Something</Label>
      </Grid>
    </TreeViewItem.Header>
  </TreeViewItem>

  <TreeViewItem>
    <TreeViewItem.Header>
      <Grid>
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="*" SharedSizeGroup="A"  />
          <ColumnDefinition Width="auto" SharedSizeGroup="B"  />
        </Grid.ColumnDefinitions>
        <Label>22.03.2000</Label>
        <Label Grid.Column="2">Something 2</Label>
      </Grid>
    </TreeViewItem.Header>
  </TreeViewItem>
</TreeView>

Note the attribute Grid.IsSharedSizeScope="True" in the TreeView and the SharedSizeGroup="A" in the Column Definitions

Upvotes: 2

Related Questions