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

推荐订阅源

OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
博客园 - 叶小钗
爱范儿
爱范儿
罗磊的独立博客
Hugging Face - Blog
Hugging Face - Blog
阮一峰的网络日志
阮一峰的网络日志
S
SegmentFault 最新的问题
Apple Machine Learning Research
Apple Machine Learning Research
美团技术团队
T
Tailwind CSS Blog
博客园 - 司徒正美
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
宝玉的分享
宝玉的分享
量子位
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Cloudflare Blog
人人都是产品经理
人人都是产品经理
小众软件
小众软件
博客园 - 【当耐特】
博客园 - 三生石上(FineUI控件)
V
Visual Studio Blog
雷峰网
雷峰网
酷 壳 – CoolShell
酷 壳 – CoolShell

博客园 - 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 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 ContentControl invoke Template from resource, reuse datatemplate 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, ItemsControl, ItemsPanelTemplate,Virt...
FredGrit · 2026-08-16 · via 博客园 - FredGrit
<Window x:Class="WpfApp14.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:WpfApp14"
        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"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Foreground" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>

        <DataTemplate DataType="{x:Type local:Book}" x:Key="BookRowDataTemplate">
            <Border BorderBrush="Gray"
                    BorderThickness="2"
                    Margin="5">
                <Grid>
                    <Grid.Resources>
                        <Style TargetType="TextBlock" BasedOn="{StaticResource TbkStyle}"/>
                    </Grid.Resources>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="4*"/>
                    </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 ISBN}" Grid.Row="0" Grid.Column="2"/>
                    <TextBlock Text="{Binding Summary}" Grid.Row="1" Grid.Column="0"/>
                    <TextBlock Text="{Binding Title}" Grid.Row="1" Grid.Column="1"/>
                    <TextBlock Text="{Binding Topic}" Grid.Row="1" Grid.Column="2"/>
                </Grid>
            </Border>
        </DataTemplate>

        <DataTemplate DataType="{x:Type local:GroupedBks}"
                      x:Key="GroupedBksDataTemplate">
            <GroupBox Header="{Binding GroupName}"
                      FontSize="50"
                      BorderBrush="Cyan"
                      BorderThickness="5"
                      Margin="10">
                <ItemsControl ItemsSource="{Binding BksList}"
                              ItemTemplate="{StaticResource BookRowDataTemplate}">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <VirtualizingStackPanel/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                </ItemsControl>
            </GroupBox>
        </DataTemplate>

        <ControlTemplate TargetType="ContentControl"
                         x:Key="GroupedControlTemplate">
            <ScrollViewer>
                <ItemsControl ItemsSource="{Binding GroupedBooks}"
                              ItemTemplate="{StaticResource GroupedBksDataTemplate}">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <VirtualizingStackPanel/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.ContextMenu>
                        <ContextMenu>
                            <MenuItem Header="Load Data"
                                      FontSize="30"
                                      Width="300"
                                      Command="{Binding LoadDataCommand}"
                                      CommandParameter="5000"/>
                        </ContextMenu>
                    </ItemsControl.ContextMenu>
                </ItemsControl>
            </ScrollViewer>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <ContentControl Template="{StaticResource GroupedControlTemplate}"/>
    </Grid>
</Window>

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

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

    public class MainVM : INotifyPropertyChanged
    {
        string originalUrl = @"http://localhost:62131/BookService.svc/getbooks?cnt=";
        HttpClient client = new HttpClient()
        {
            Timeout = TimeSpan.FromMinutes(10)
        };

        private bool isLoading = false;

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

        private ICommand loadDataCommand;
        public ICommand LoadDataCommand
        {
            get
            {
                if (loadDataCommand == null)
                {
                    loadDataCommand = new DelegateCommand(LoadDataCommandExecuted);
                }
                return loadDataCommand;
            }
        }

        private void LoadDataCommandExecuted(object? obj)
        {
            if (Int32.TryParse(obj?.ToString(), out int num))
            {
                _ = GetStringAsync(num);
            }
        }

        private async Task GetStringAsync(int cnt = 1000)
        {
            if (isLoading)
            {
                return;
            }
            isLoading = true;
            string url = $"{originalUrl}{cnt}";
            try
            {
                string xmlStr = await client.GetStringAsync(url);
                var bksList = StringReaderDeserialize(xmlStr);
                var tempGroups = bksList.GroupBy(x => x.CategoryName);
                if (tempGroups != null && tempGroups.Any())
                {
                    GroupedBooks = new ObservableCollection<GroupedBks>();
                    foreach (var group in tempGroups)
                    {
                        GroupedBooks.Add(new GroupedBks()
                        {
                            GroupName = group.Key,
                            BksList = group.ToList()
                        });
                    }
                }
            }
            finally
            {
                isLoading = false;
            }
        }

        private List<Book> StringReaderDeserialize(string xmlStr)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(XmlBook));
            using (StringReader reader = new StringReader(xmlStr))
            {
                var xmlBk = xmlSerializer.Deserialize(reader) as XmlBook;
                if (xmlBk != null)
                {
                    return xmlBk.BksList;
                }
            }
            return null;
        }

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

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

        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));
        }
    }

    public class DelegateCommand : ICommand
    {
        private Action<object?> execute;
        private Func<object?, bool>? canExecute;
        public DelegateCommand(Action<object?> executeValue, Func<object?, bool>? canExecuteValue = null)
        {
            execute = 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);
                }
            }
        }
    }

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

    public class XmlNode
    {
        public string NodeName { get; set; }
        public string NodeValue { get; set; }
        public List<XmlNode> NodeChildren { get; set; }
        public XmlNode()
        {
            NodeChildren = new List<XmlNode>();
        }
    }


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

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

image

image

//WCF

//D:\C\WcfService6\WcfService6\IBookService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService6
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IBookService" in both code and config file together.
    [ServiceContract]
    public interface IBookService
    {
        [OperationContract]
        [WebGet(UriTemplate = "/getbooks?cnt={cnt}")]
        List<Book> GetBooks(int cnt = 1000);
    }


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

    enum BookCategory
    {
        Science,
        Technology,
        Engineering,
        Math
    }
}


//using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Threading;

namespace WcfService6
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "BookService" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select BookService.svc or BookService.svc.cs at the Solution Explorer and start debugging.
    public class BookService : IBookService
    {
        private static long Id = 1;
        private static string[] enumNames = Enum.GetNames(typeof(BookCategory));
        private static int enumsLength = enumNames.Length;

        private static (long, long) GetStartEnd(int interval)
        {
            long end = Interlocked.Add(ref Id, interval);
            long start = end - interval;
            return (start, end);
        }

        public List<Book> GetBooks(int cnt = 1000)
        {
            List<Book> bksList = new List<Book>();
            var (start, end) = GetStartEnd(cnt);
            for (long i = start; i < end; i++)
            {
                bksList.Add(new Book()
                {
                    Id = i,
                    Name = $"Name_{i}",
                    ISBN = $"ISBN_{i}_{Guid.NewGuid():N}",
                    CategoryName = $"{enumNames[i % enumsLength]}",
                    Summary = $"Summary_{i}",
                    Title = $"Title_{i}",
                    Topic = $"Topic_{i}"
                });
            }
            return bksList;
        }
    }
}


//D:\C\WcfService6\WcfService6\Web.config
<?xml version="1.0"?>
<configuration>

    <appSettings>
        <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
    </appSettings>
    <system.web>
        <compilation debug="true" targetFramework="4.8" />
        <httpRuntime targetFramework="4.8"/>
    </system.web>
    <system.serviceModel>
        <bindings>
            <webHttpBinding>
                <binding name="BookServiceWebHttpBinding"
                         maxBufferPoolSize="2147483647"
                         maxBufferSize="2147483647"
                         maxReceivedMessageSize="2147483647">
                    <readerQuotas maxArrayLength="2147483647"
                                  maxBytesPerRead="2147483647"
                                  maxDepth="2147483647"
                                  maxNameTableCharCount="2147483647"
                                  maxStringContentLength="2147483647"/>
                    <security mode="None"/>
                </binding>
            </webHttpBinding>
        </bindings>
        <behaviors>
            <serviceBehaviors>
                <behavior name="BookServiceBehavior">
                    <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
                    <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
                    <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                    <serviceDebug includeExceptionDetailInFaults="false"/>
                </behavior>
            </serviceBehaviors>
            <endpointBehaviors>
                <behavior name="BookServiceEndPointBehavior">
                    <webHttp/>
                </behavior>
            </endpointBehaviors>
        </behaviors>
        <protocolMapping>
            <add binding="basicHttpsBinding" scheme="https" />
        </protocolMapping>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
        <services>
            <service name="WcfService6.BookService"
                     behaviorConfiguration="">
                <endpoint address=""
                          binding="webHttpBinding"
                          contract="WcfService6.IBookService"
                          behaviorConfiguration="BookServiceEndPointBehavior"
                          bindingConfiguration="BookServiceWebHttpBinding"/>
            </service>
        </services>
    </system.serviceModel>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
        <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
        <directoryBrowse enabled="true"/>
    </system.webServer>

</configuration>