WPF TreeViewItem style when mouseover, totally changes in foreground,fontweight,background via listen on treeviewitem

<Window x:Class="WpfApp5.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:WpfApp5"
        mc:Ignorable="d"
        Title="MainWindow" WindowState="Maximized">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Window.Resources>
        <Style TargetType="TextBlock" x:Key="TbkStyle">
            <Setter Property="FontSize" Value="30"/>
            <Setter Property="Margin" Value="5"/>
            <Setter Property="Foreground" Value="Black"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=TreeViewItem}}" Value="True">
                    <Setter Property="Foreground" Value="Red"/>
                    <Setter Property="FontWeight" Value="ExtraBold"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>

        <DataTemplate DataType="{x:Type local:Book}" x:Key="BookTemplate">
            <Border BorderBrush="Cyan"
                    BorderThickness="2">
                <Grid Margin="0,10" 
                  Width="{x:Static SystemParameters.FullPrimaryScreenWidth}">
                    <Grid.Resources>
                        <Style TargetType="TextBlock" BasedOn="{StaticResource TbkStyle}"/>
                    </Grid.Resources>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Id}"/>
                    <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding CategoryName}"/>
                    <TextBlock Grid.Row="0" Grid.Column="2" Text="{Binding Name}"/>
                    <TextBlock Grid.Row="1" Grid.Column="0" Text="{Binding Comment}"/>
                    <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Content}"/>
                    <TextBlock Grid.Row="1" Grid.Column="2" Text="{Binding Author}"/>
                    <TextBlock Grid.Row="2" Grid.Column="0" Text="{Binding Summary}"/>
                    <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Title}"/>
                    <TextBlock Grid.Row="2" Grid.Column="2" Text="{Binding Topic}"/>
                    <TextBlock Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="3" Text="{Binding ISBN}"/>
                </Grid>
            </Border>
        </DataTemplate>

        <HierarchicalDataTemplate DataType="{x:Type local:GroupedBooks}"
                                  ItemsSource="{Binding BksList}"
                                  ItemTemplate="{StaticResource BookTemplate}"
                                  x:Key="TreeViewItemTemplate">
            <GroupBox BorderBrush="LightCyan"
                      BorderThickness="2"
                      Header="{Binding GroupName}"
                      FontSize="50" 
                     >
                <GroupBox.Style>
                    <Style TargetType="GroupBox">
                        <Setter Property="Foreground" Value="Blue"/>
                        <Setter Property="FontWeight" Value="Normal"/>
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=TreeViewItem}}" Value="True">
                                <Setter Property="Foreground" Value="Red"/>
                                <Setter Property="FontWeight" Value="ExtraBold"/>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </GroupBox.Style>
            </GroupBox>
        </HierarchicalDataTemplate>

        <Style TargetType="TreeViewItem">
            <Setter Property="Margin" Value="0,10"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="LightYellow"/>
                </Trigger>
            </Style.Triggers>
        </Style>

        <ControlTemplate TargetType="ContentControl"
                         x:Key="TreeViewTemplate">
            <TreeView ItemsSource="{Binding GroupedBksCollection}"
                      ItemTemplate="{StaticResource TreeViewItemTemplate}"/>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <ContentControl Template="{StaticResource TreeViewTemplate}"/>
    </Grid>
</Window>



using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp5
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }


    public class MainVM : INotifyPropertyChanged
    {
        static string url = "http://localhost:5000/api/books/getbooks/100";
        static HttpClient client = new HttpClient()
        {
            Timeout = TimeSpan.FromMinutes(1)
        };

        public MainVM()
        {
            if(!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                _ = LoadDataAsync();
            }           
        }

        private async Task LoadDataAsync()
        {
            string jsonStr = await client.GetStringAsync(url);
            if (!string.IsNullOrWhiteSpace(jsonStr))
            {
                var bks = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Book>>(jsonStr);
                if(bks!=null && bks.Any())
                {
                    var groupedBks = bks.GroupBy(x => x.CategoryName);
                    if (groupedBks != null && groupedBks.Any())
                    {
                        GroupedBksCollection = new ObservableCollection<GroupedBooks>();
                        foreach(var g in groupedBks)
                        {
                            GroupedBksCollection.Add(new GroupedBooks()
                            {
                                GroupName = g.Key,
                                BksList = g.ToList()
                            });
                        }
                    }
                }                
            }
        }

        private ObservableCollection<GroupedBooks> groupedBksCollection;
        public ObservableCollection<GroupedBooks> GroupedBksCollection
        {
            get
            {
                return groupedBksCollection;
            }
            set
            {
                if (value != groupedBksCollection)
                {
                    groupedBksCollection = value;
                    OnPropertyChanged();
                }
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {

            var handler = Volatile.Read(ref PropertyChanged);
            if (handler == null)
            {
                return;
            }
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class GroupedBooks
    {
        public string GroupName { get; set; }
        public List<Book> BksList { get; set; }
    }

    public class Book
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Author { get; set; }
        public string ISBN { get; set; }
        public string Comment { get; set; }
        public string Content { get; set; }
        public string Summary { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
        public string CategoryName { get; set; }
    }

}

 

 

 

 

image

 

 

 

 

 

 

image

 

 

 

 

 

 

 

posted @ 2026-09-27 12:30  FredGrit  阅读(5)  评论(0)    收藏  举报