在WPF树视图中单击时如何更改TreeViewItem的背景颜色?

时间:2018-11-12 08:30:08

标签: c# wpf treeview

我想在单击TextBlock时更改StackPanel的背景。

enter image description here

现在背景是蓝色的!我要更改它!

<TreeView  Name="tvView" HorizontalAlignment="Left"  VerticalAlignment="Top"   BorderThickness="0">

        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Path=ChildNodes}">
                <Grid VerticalAlignment="Top" Margin="0">
                    <StackPanel Orientation="Horizontal" d:LayoutOverrides="Height">
                        <TextBlock Name="ConfidenceLevelReminderText" Text="!" FontWeight="Bold" HorizontalAlignment="Center" Foreground="#FF0000" Width="{Binding Path=ConfidenceLevelWidth}" Margin="0,0,0,0"></TextBlock>
                        <TextBlock TextWrapping="Wrap" 
                                   Padding="0,3,0,3" 
                                   Text="{Binding Path=Name}" 
                                   ToolTip="{Binding Path=NameToolTip}" 
                                   Tag="{Binding Path=TagInfo}" 
                                   MouseLeftButtonDown="name_MouseLeftButtonDown" 
                                   FontSize="14" 
                                   VerticalAlignment="Center" 
                                   HorizontalAlignment="Center" 
                                   Foreground="#FF666666" 
                                   Margin="0" 
                                   Width="{Binding Path=TextWidth}" 
                                   Cursor="Hand"/>
                        <Button x:Name="btnIngnore" Width="{Binding Path=IgnoreWidth}" Click="btn_ignore_Click" Tag="{Binding Path=NodeId}" Margin="0"  BorderThickness="0" Background="{x:Null}" Style="{StaticResource ButtonStyle32}" IsEnabled="{Binding Path=IgnoreWidth,Converter={StaticResource itb}}"  Cursor="Hand">
                            <TextBlock Text="xxxx" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0" FontSize="12" Foreground="#FF666666"/>
                        </Button>

                    </StackPanel>
                </Grid>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>

1 个答案:

答案 0 :(得分:1)

如果需要

  

在单击TextBlock时更改StackPanel的背景。

您可以将EventSetter添加到TextBlock的样式中,并在事件处理程序中处理事件。

<TextBlock Text="...">
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <EventSetter Event="MouseDown" Handler="Mouse_LBtnDown"/>
        </Style>
    </TextBlock.Style>
</TextBlock>

private void Mouse_LBtnDown(object sender, MouseButtonEventArgs e)
{
    StackPanel stp = null;
    var visParent = VisualTreeHelper.GetParent(sender as FrameworkElement);
    while (stp == null && visParent != null)
    {
        stp = visParent as StackPanel;
        visParent = VisualTreeHelper.GetParent(visParent);
    }
    if (stp == null) { return; }

    stp.Background = Brushes.Coral;
}

要使其可重用和可调,可以从事件处理程序中进行操作。

如果您不想要所要询问的内容,请重新考虑您的问题并提出新的问题。