惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
Recent Announcements
Recent Announcements
雷峰网
雷峰网
The GitHub Blog
The GitHub Blog
罗磊的独立博客
月光博客
月光博客
J
Java Code Geeks
A
About on SuperTechFans
Microsoft Security Blog
Microsoft Security Blog
D
Docker
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
F
Fortinet All Blogs
U
Unit 42
C
Check Point Blog
Martin Fowler
Martin Fowler
有赞技术团队
有赞技术团队
博客园 - 叶小钗
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
Blog — PlanetScale
Blog — PlanetScale
大猫的无限游戏
大猫的无限游戏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
阮一峰的网络日志
阮一峰的网络日志
MyScale Blog
MyScale Blog

博客园 - FredGrit

WPF customize via three combied custom controls WPF DataGrid DataGridTemplateColumn DataTemplate ContentPresenter ContentTemplate WPF Customcontrol NumUpDownScroller WPF CustomControl override Template in Generic.xaml and invoke different style WPF HierarchicalDataTemplate customize via ToggleButton WPF DataGrid DataGridTemplateColumn DataTemplate call predefined DataTemplate via ContentPresenter and ContentTemplate WPF ListBox load data via contentcontrol an ItemTemplate WPF DataGrid load data from Asp.Net Core WebAPI WPF TreeView HierarchicalDataTemplate with grouped Data WPF display grouped data with GroupBox and ItemsControl WPF two listbox scroll syncchronously via behavior WPF invoke data from WebAPI,DataGridTemplate call pre defined DataTemplate via ContentPresenter WPF ListBox load data from WCF WPF datagrid load data from WCF via json, export selected items to json file WPF ItemsControl load data from WCF,DataTemplate, ContentControl WPF customize rotated wheel relentlessly via custom control WPF embed DataTemplate in HierchicalDataTemplate of TreeView WPF ContentControl, ItemsControl, ItemsPanelTemplate,VirtualizingStackPanel,convert xml string to List<T> WPF parse web.config recursively, TreeView and HierarchicalDataTemplate WPF Custom control in cs and Generic.xaml WPF ContextMenu independent visual tree resolved via Freezable implemented class WPF custom control GetTemplateChild vs FindName,NameScope separation between Logical Tree and Visual Tree, WPF ListBox ListView Datatemplate, parse xml to List via XmlSerializer and StringReader WPF TreeView HierarchicalDataTemplate, parse xml via traverse in XmlElement WPF parse xml via [XmRoot] and [XmlElement] attributes together, contentcontrol's template is ControlTemplate from Resources WPF deserialize xml string as List via [XmlRoot] and [XmlElement] attribute WPF ContentControl Template WPF DatagridTemplate Binding DataTemplate WPF TreeView explicitly given key name to HierarchicalDataTemplate WPF, parse XMlDocument as List
WPF ContentControl invoke Template from resource, reuse d...
FredGrit · 2026-07-25 · via 博客园 - FredGrit
<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="FontWeight" Value="Normal"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Foreground" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>

        <DataTemplate DataType="{x:Type local:Book}"
                      x:Key="RowDataTemplate">
            <Border BorderBrush="LightGray"
                    BorderThickness="1"
                    Margin="5">
                <Grid>
                    <Grid.Resources>
                        <Style TargetType="TextBlock" BasedOn="{StaticResource TbkStyle}"/>
                    </Grid.Resources>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="{Binding Id}" Grid.Row="0" Grid.Column="0"/>
                    <TextBlock Text="{Binding Name}" Grid.Row="0" Grid.Column="1"/>
                    <TextBlock Text="{Binding Author}" Grid.Row="1" Grid.Column="0"/>
                    <TextBlock Text="{Binding Comment}" Grid.Row="1" Grid.Column="1"/>
                    <TextBlock Text="{Binding Content}" Grid.Row="2" Grid.Column="0"/>
                    <TextBlock Text="{Binding Summary}" Grid.Row="2" Grid.Column="1"/>
                    <TextBlock Text="{Binding Title}" Grid.Row="3" Grid.Column="0"/>
                    <TextBlock Text="{Binding Topic}" Grid.Row="3" Grid.Column="1"/>
                    <TextBlock Text="{Binding ISBN}" Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2"/>
                </Grid>
            </Border>
        </DataTemplate>

        <DataTemplate DataType="{x:Type local:GroupedBook}"
                      x:Key="GroupDataTemplate">
            <GroupBox Header="{Binding GroupName}"
                      FontSize="50"
                      FontWeight="ExtraBold"
                      BorderBrush="LightBlue"
                      BorderThickness="2"
                      Margin="5">
                <ItemsControl ItemsSource="{Binding Bks}"
                              ItemTemplate="{StaticResource RowDataTemplate}"
                              Margin="5"
                              VirtualizingPanel.IsVirtualizing="True"
                              VirtualizingPanel.VirtualizationMode="Recycling"
                              VirtualizingPanel.CacheLength="5,5"
                              VirtualizingPanel.CacheLengthUnit="Item"
                              UseLayoutRounding="True"
                              SnapsToDevicePixels="True"
                              ScrollViewer.CanContentScroll="True"
                              ScrollViewer.IsDeferredScrollingEnabled="True">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <VirtualizingStackPanel/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.Resources>
                        <Style TargetType="TextBlock" BasedOn="{StaticResource TbkStyle}"/>
                    </ItemsControl.Resources>
                </ItemsControl>
            </GroupBox>
        </DataTemplate>

        <ControlTemplate  TargetType="ContentControl" 
                          x:Key="ContentControlTemplate">
            <ScrollViewer>
                <ItemsControl ItemsSource="{Binding GroupedBks}"
                              ItemTemplate="{StaticResource GroupDataTemplate}"
                              VirtualizingPanel.IsVirtualizing="True"
                              VirtualizingPanel.VirtualizationMode="Recycling"
                              VirtualizingPanel.CacheLengthUnit="Item"
                              VirtualizingPanel.CacheLength="5,5"
                              ScrollViewer.CanContentScroll="True"
                              ScrollViewer.IsDeferredScrollingEnabled="True"
                              UseLayoutRounding="True"
                              SnapsToDevicePixels="True">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <VirtualizingStackPanel/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.ContextMenu>
                        <ContextMenu>
                            <MenuItem Header="Refresh"
                                      Command="{Binding RefreshDataCommad}"/>
                        </ContextMenu>
                    </ItemsControl.ContextMenu>
                </ItemsControl>
            </ScrollViewer>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <ContentControl Template="{StaticResource ContentControlTemplate}"/>
    </Grid>
</Window>



using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
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;
using System.Xml.Serialization;

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

    public class MainVM : INotifyPropertyChanged
    {
        private static HttpClient client = new HttpClient()
        {
            Timeout = TimeSpan.FromSeconds(120)
        };

        string serviceUrl = "http://localhost:56293/BookService.svc/getbooks?cnt=";
        private CancellationTokenSource _cts = new CancellationTokenSource();
        private Task _loadTask;

        public DelegateCommand RefreshDataCommad { get; }

        public MainVM()
        {
            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                _loadTask = LoadBooksAsync(10, _cts.Token);
                RefreshDataCommad = new DelegateCommand(RefreshDataCommadExecuted);
            }
        }

        private void RefreshDataCommadExecuted(object? obj)
        {
            //_ = LoadBooksAsync();
        }

        private async Task LoadBooksAsync(int cnt = 1000000, CancellationToken token = default)
        {
            if (_cts.IsCancellationRequested)
            {
                return;
            }
            string url = $"{serviceUrl}{cnt}";
            string xmlStr = await client.GetStringAsync(url);
            var bks = ParseXmlStr(xmlStr);
            var groups = bks.GroupBy(x => x.CategoryName);
            if (groups != null && groups.Any())
            {
                GroupedBks = new ObservableCollection<GroupedBook>();
                foreach (var g in groups)
                {
                    GroupedBks.Add(new GroupedBook()
                    {
                        GroupName = g.Key,
                        Bks = g.ToList()
                    });
                }
            }
        }

        private List<Book> ParseXmlStr(string xmlStr)
        {
            try
            {
                var serializer = new XmlSerializer(typeof(BookList));
                using (var reader = new StringReader(xmlStr))
                {
                    var bksList = serializer.Deserialize(reader) as BookList;
                    if (bksList != null)
                    {
                        return bksList.Bks;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex?.Message);
            }
            return null;
        }

        private ObservableCollection<GroupedBook> _groupedBks;
        public ObservableCollection<GroupedBook> GroupedBks
        {
            get
            {
                return _groupedBks;
            }
            set
            {
                if (value != _groupedBks)
                {
                    _groupedBks = value;
                    OnPropertyChanged();
                }
            }
        }

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

    public class GroupedBook
    {
        public string GroupName { get; set; }
        public List<Book> Bks { get; set; }
    }

    [XmlRoot("ArrayOfBook", Namespace = "http://schemas.datacontract.org/2004/07/WcfService2")]
    public class BookList
    {
        [XmlElement("Book")]
        public List<Book> Bks { get; set; }
    }

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

    public class DelegateCommand : ICommand
    {
        private readonly Action<object?> _execute;
        private Func<object?, bool>? _canExecute;
        public DelegateCommand(Action<object?> execute, Func<object?, bool>? canExecute = null)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
            _canExecute = canExecute;
        }

        public event EventHandler? CanExecuteChanged;

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

        public void Execute(object? parameter)
        {
            _execute?.Invoke(parameter);
        }

        public void RaiseCanExecutedChanged(object sender,EventArgs e)
        {
            var handler = Volatile.Read(ref CanExecuteChanged);
            if(handler==null)
            {
                return;
            }

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

image