views:

47

answers:

1

Hi, I'm trying to customize the TreeView control. When a user selects an item in the TreeView, I need the ActualWidth of the selected item to be stored in the item's Tag:

 <Style x:Key="{x:Type TreeViewItem}" TargetType="{x:Type TreeViewItem}">
           <!-- ... -->
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type TreeViewItem}">
                        <Grid ShowGridLines="True">

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

                            <Rectangle x:Name="rect" />

                            <ContentPresenter x:Name="PART_Header" ContentSource="Header" Margin="5" />         

                            <ItemsPresenter x:Name="ItemsHost" Grid.Row="1" Grid.Column="1" />
                            <!-- ... -->       
                        </Grid>

                        <ControlTemplate.Triggers>
                            <Trigger Property="IsSelected" Value="true">
                                <Setter Property="Tag" Value="{Binding ElementName=rect, Path=ActualWidth}" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

Later, I listen to the "SelectedItemChanged" event of the TreeView:

private void views_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        TreeViewItem item = (TreeViewItem)e.NewValue;
        double i = (double)item.Tag;
    }

Now the problem is that item.Tag is always null. Is this a problem with my binding? Or should things be done in a different way?

+1  A: 

Try that :

<Setter Property="Tag" Value="{Binding Path=ActualWidth, RelativeSource={x:Static RelativeSource.Self}}" />
Thomas Levesque
This one works but it doesn't give me the value that I need--it's binding to the ActualWidth of the item, which is equal to the width of the TreeView where it will be placed. If I want the ActualWidth of contents of the item, I need to bind it either to the rectangle 'rect' or to the first column definition.
Austin