Silverlight:如何在选择时更改TreeViewItem文本颜色

时间:2009-11-12 21:32:01

标签: silverlight treeview hierarchicaldatatemplate treeviewitem

我在HierarchicalDataTemplate中有TextBlock。选择TreeViewItem时,我需要将前景色设置为红色。

<controls:TreeView  Background="#FF939597"
      ScrollViewer.HorizontalScrollBarVisibility="Disabled" x:Name="CommentTreeView" Margin="0,0,0,118"
            ItemContainerStyle="{StaticResource SectionsTreeViewItemStyle}">
                <controls:TreeView.ItemTemplate>
                    <control:HierarchicalDataTemplate ItemsSource="{Binding SubSections}" ItemContainerStyle="{StaticResource SectionsTreeViewItemStyle}">
                    <Grid>

                    <TextBlock x:Name="ItemTextBlock" Margin="0,6,48,0"
                               <!-- ??? Foreground="Red" ??? if item selected ??? -->
                                         FontSize="11"  Text="{Binding Path=Name}" 
                                         TextWrapping="Wrap" VerticalAlignment="Top">
                    </TextBlock>

                </Grid>

                </control:HierarchicalDataTemplate>
            </controls:TreeView.ItemTemplate>
        </controls:TreeView>

1 个答案:

答案 0 :(得分:1)

您可以使用SilverS的RelativeSource自定义实现来执行此操作:

http://www.codeproject.com/Articles/36500/Implementing-RelativeSource-binding-in-Silverlight.aspx

<UserControl.Resources>
    <Converters:BackgroundConverter x:Key="BackgroundConverter"/>
</UserControl.Resources>

    <controls:TreeView Background="#FF939597"
          ScrollViewer.HorizontalScrollBarVisibility="Disabled" x:Name="CommentTreeView" Margin="0,0,0,118"
                ItemContainerStyle="{StaticResource SectionsTreeViewItemStyle}">
                    <controls:TreeView.ItemTemplate>
                        <control:HierarchicalDataTemplate ItemsSource="{Binding SubSections}" ItemContainerStyle="{StaticResource SectionsTreeViewItemStyle}">

                            <Grid>

                            <TextBlock x:Name="ItemTextBlock" Margin="0,6,48,0"
                                                 FontSize="11"  Text="{Binding Path=Name}" 
                                                 TextWrapping="Wrap" VerticalAlignment="Top">
                                                            <local:BindingHelper.Binding>
                                    <local:BindingProperties TargetProperty="Foreground" SourceProperty="IsSelected"
                                                             Converter="{StaticResource BackgroundConverter}"
                                                             RelativeSourceAncestorType="TreeViewItem"/>
                                </local:BindingHelper.Binding>
                            </TextBlock>

                        </Grid>

                        </control:HierarchicalDataTemplate>
                    </controls:TreeView.ItemTemplate>
                </controls:TreeView>
相关问题