WPF TemplateBinding is oneway and can't trigger change except at first, the alternative is to use Binding and relativesource

 <ListBox Grid.Column="0"
          Grid.Row="1"
          ItemsSource="{TemplateBinding CategoryList}"
          SelectedItem="{TemplateBinding LbxSelectedItem}"/>



The TemplateBinding is oneway, and can't trigger except the first chance, if you want to implement SelectedItem changes and triggers action, use Binding and RelativeSource 


 <ListBox Grid.Column="0"
          Grid.Row="1"
          ItemsSource="{TemplateBinding CategoryList}"
          SelectedItem="{Binding LbxSelectedItem,RelativeSource={RelativeSource AncestorType=local:TreeVierwControl},Mode=TwoWay}"/>

 

 

//D:\C\WpfApp4\Models\Book.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace WpfApp4.Models
{
    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; }
    }
}


//D:\C\WpfApp4\Models\DelegateCommand.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Input;

namespace WpfApp4.Models
{
    public class DelegateCommand : ICommand
    {
        private readonly Action<Object?> execute;
        private readonly Func<object?, bool>? canExecute;

        public DelegateCommand(Action<Object?> executeValue, Func<object?, bool>? canExecuteValue = null)
        {
            execute = executeValue ?? throw new ArgumentNullException(nameof(executeValue));
            canExecute = canExecuteValue;
        }

        public event EventHandler? CanExecuteChanged;

        public bool CanExecute(object? parameter)
        {
            return canExecute == null ? true : canExecute(parameter);
        }

        public void Execute(object? parameter)
        {
            execute(parameter);
        }

        public void RaiseCanExecuteChanged()
        {
            var handler = Volatile.Read(ref CanExecuteChanged);
            if(handler==null)
            {
                return;
            }

            var dispatcher = Application.Current?.Dispatcher;
            if(dispatcher!=null)
            {
                if(dispatcher.CheckAccess())
                {
                    handler(this, EventArgs.Empty);
                }
                else
                {
                    dispatcher.Invoke(() =>
                    {
                        handler(this, EventArgs.Empty);
                    }, System.Windows.Threading.DispatcherPriority.Background);
                }                
            }
        }
    }
}


//D:\C\WpfApp4\Themes\Generic.xaml
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApp4">


    <Style TargetType="{x:Type local:TreeVierwControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:TreeVierwControl}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto"/>
                                <RowDefinition Height="*"/>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="200"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                            <Button Grid.Row="0"
                                    Grid.Column="0"
                                    Content="Load Data"
                                    FontSize="30"
                                    Command="{TemplateBinding LoadDataCommand}"
                                    Margin="5,0"/>
                            <ListBox Grid.Column="0"
                                     Grid.Row="1"
                                     ItemsSource="{TemplateBinding CategoryList}"
                                     SelectedItem="{Binding LbxSelectedItem,RelativeSource={RelativeSource AncestorType=local:TreeVierwControl},Mode=TwoWay}">
                                <ListBox.Resources>
                                    <Style TargetType="ListBoxItem">
                                        <Setter Property="FontSize" Value="30"/>
                                        <Style.Triggers>
                                            <Trigger Property="IsSelected" Value="True">
                                                <Setter Property="Foreground" Value="Red"/>
                                                <Setter Property="FontWeight" Value="ExtraBold"/>
                                            </Trigger>
                                        </Style.Triggers>
                                    </Style>
                                </ListBox.Resources>
                            </ListBox>
                            <DataGrid Grid.Column="1"
                                      Grid.Row="1"
                                      ItemsSource="{TemplateBinding CategoryBksCollection}"
                                      AutoGenerateColumns="True"
                                      CanUserAddRows="False"
                                      HeadersVisibility="Column"
                                      VirtualizingPanel.IsVirtualizing="True"
                                      VirtualizingPanel.VirtualizationMode="Recycling"
                                      VirtualizingPanel.CacheLength="5,5"
                                      VirtualizingPanel.CacheLengthUnit="Item"
                                      ScrollViewer.CanContentScroll="True"
                                      ScrollViewer.IsDeferredScrollingEnabled="True"
                                      UseLayoutRounding="True">
                                <DataGrid.Resources>
                                    <Style TargetType="DataGridRow">
                                        <Setter Property="FontSize" Value="30"/>
                                        <Style.Triggers>
                                            <Trigger Property="IsMouseOver" Value="True">
                                                <Setter Property="Foreground" Value="Red"/>
                                                <Setter Property="FontWeight" Value="ExtraBold"/>
                                            </Trigger>
                                        </Style.Triggers>
                                    </Style>
                                </DataGrid.Resources>
                            </DataGrid>
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>


//D:\C\WpfApp4\MainWindow.xaml
<Window x:Class="WpfApp4.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:WpfApp4"
        mc:Ignorable="d"
        Title="{Binding MainTitle}" WindowState="Maximized">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Grid>
        <local:TreeVierwControl
            CategoryList="{Binding CategoryCollection}"
            CategoryBksCollection="{Binding BksCollection}"
            LbxSelectedItem="{Binding SelectedCategory,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
            LoadDataCommand="{Binding LoadCommand}"/>
    </Grid>
</Window>

//D:\C\WpfApp4\MainWindow.xaml.cs
using Newtonsoft.Json;
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.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WpfApp4.Models;

namespace WpfApp4
{
    /// <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/1000000";
        static HttpClient client = new HttpClient()
        {
            Timeout = TimeSpan.FromSeconds(60)
        };
        static bool isLoading = false;
        List<Book> bksList = new List<Book>();

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string propName = "")
        {
            var handler = Volatile.Read(ref PropertyChanged);
            if (handler == null)
            {
                return;
            }
            handler(this, new PropertyChangedEventArgs(propName));
        }


        private ObservableCollection<string> categoryCollection;
        public ObservableCollection<string> CategoryCollection
        {
            get
            {
                return categoryCollection;
            }
            set
            {
                if (value != categoryCollection)
                {
                    categoryCollection = value;
                    OnPropertyChanged();
                }
            }
        }

        private string selectedCategory;
        public string SelectedCategory
        {
            get
            {
                return selectedCategory;
            }
            set
            {
                if (value != selectedCategory)
                {
                    selectedCategory = value;
                    OnPropertyChanged();
                    OnSelectedCategoryChanged();
                }
            }
        }

        private void OnSelectedCategoryChanged()
        {
            BksCollection = new ObservableCollection<Book>(bksList.Where(x => x.CategoryName == SelectedCategory));
        }

        private ObservableCollection<Book> bksCollection;
        public ObservableCollection<Book> BksCollection
        {
            get
            {
                return bksCollection;
            }
            set
            {
                if (value != bksCollection)
                {
                    bksCollection = value;
                    OnPropertyChanged();
                }
            }
        }

        private ICommand loadCommand;
        public ICommand LoadCommand
        {
            get
            {
                if (loadCommand == null)
                {
                    loadCommand = new DelegateCommand(s =>
                    {
                        _ = LoadCommandExecuted(s);
                    });
                }
                return loadCommand;
            }
        }

        private async Task LoadCommandExecuted(object? obj)
        {
            if (isLoading)
            {
                return;
            }
            isLoading = true;

            try
            {
                string jsonStr = await client.GetStringAsync(url);
                bksList = JsonConvert.DeserializeObject<List<Book>>(jsonStr).ToList();
                if(bksList != null && bksList.Any())
                {
                    var groupedBks = bksList.GroupBy(x => x.CategoryName);
                    CategoryCollection = new ObservableCollection<string>(groupedBks.Select(x => x.Key).Distinct());
                    SelectedCategory = CategoryCollection.FirstOrDefault();
                    BksCollection = new ObservableCollection<Book>(groupedBks.Where(x=>x.Key==SelectedCategory).SelectMany(x=>x));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex?.Message);
            }
            finally
            {
                isLoading = false;
            }
        }
    }
}

 

 

 

 

 

 

 

image

 

 

 

 

 

 

image

 

 

 

 

 

 

 

 

image

 

 

 

 

image

 

posted @ 2026-09-27 10:42  FredGrit  阅读(4)  评论(0)    收藏  举报