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

推荐订阅源

月光博客
月光博客
Apple Machine Learning Research
Apple Machine Learning Research
IT之家
IT之家
阮一峰的网络日志
阮一峰的网络日志
雷峰网
雷峰网
S
SegmentFault 最新的问题
量子位
有赞技术团队
有赞技术团队
V
V2EX
宝玉的分享
宝玉的分享
Hugging Face - Blog
Hugging Face - Blog
B
Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Jina AI
Jina AI
C
Check Point Blog
G
Google Developers Blog
博客园 - 叶小钗
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园_首页
T
Tailwind CSS Blog
B
Blog RSS Feed
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
酷 壳 – CoolShell
酷 壳 – CoolShell
U
Unit 42

博客园 - 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 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 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 datagrid load data from WCF via json, export selected...
FredGrit · 2026-08-23 · via 博客园 - FredGrit
//WPF
<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>
    <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"/>
                    <Setter Property="FontWeight" Value="ExtraBold"/>
                </Trigger>
            </Style.Triggers>
        </Style>

        <ControlTemplate TargetType="ContentControl"
                         x:Key="DGControlTemplate">
            <DataGrid ItemsSource="{Binding BksCollection}"
                      AutoGenerateColumns="True"
                      CanUserAddRows="False"
                      VirtualizingPanel.IsVirtualizing="True"
                      VirtualizingPanel.VirtualizationMode="Recycling"
                      VirtualizingPanel.CacheLength="2,2"
                      VirtualizingPanel.CacheLengthUnit="Item"
                      ScrollViewer.CanContentScroll="True"
                      ScrollViewer.IsDeferredScrollingEnabled="True"
                      UseLayoutRounding="True"
                      SnapsToDevicePixels="True">
                <DataGrid.Resources>
                    <Style TargetType="DataGridRow">
                        <Setter Property="FontSize" Value="30"/>
                        <Setter Property="FontWeight" Value="Normal"/>
                        <Style.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Foreground" Value="Red"/>
                                <Setter Property="FontWeight" Value="ExtraBold"/>
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </DataGrid.Resources>
                <DataGrid.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Load Data"
                                  Command="{Binding LoadCommand}"
                                  FontSize="30"
                                  Width="300"/>
                        <MenuItem Header="Export Selected"
                                  Command="{Binding ExportSelectedDataCommand}"
                                  CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},
                                  Path=PlacementTarget.SelectedItems}"
                                  Width="300"
                                  FontSize="30"/>
                    </ContextMenu>
                </DataGrid.ContextMenu>
            </DataGrid>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <ContentControl Template="{StaticResource DGControlTemplate}"/>
    </Grid>
</Window>


using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
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 Microsoft.Win32;
using Newtonsoft.Json;

namespace WpfApp4
{
    /// <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.FromHours(1)
        };

        private static string originUrl = "http://localhost:59166/BookService.svc/getbooks?cnt=";
        private bool isLoading = false;
        private string tempMsg = "";
        public MainVM()
        {
            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                SetMainTitle(GetTimeNow());
                _ = InitBooksCollectionAsync();
            }
        }

        private async Task InitBooksCollectionAsync(int cnt = 1000000)
        {
            if (isLoading)
            {
                return;
            }
            isLoading = true;
            tempMsg = $"{GetTimeNow()},start loading...";
            SetMainTitle(tempMsg);
            try
            {
                string url = $"{originUrl}{cnt}";
                string jsonStr = await client.GetStringAsync(url);
                List<Book> bksList = JsonConvert.DeserializeObject<List<Book>>(jsonStr);
                if (bksList != null && bksList.Any())
                {
                    BksCollection = new ObservableCollection<Book>(bksList);
                    tempMsg = $"{GetTimeNow()},FirstId:{BksCollection?.FirstOrDefault()?.Id}," +
                        $"LastId:{BksCollection?.LastOrDefault()?.Id}";
                    SetMainTitle(tempMsg);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex?.Message);
            }
            finally
            {
                isLoading = false;
            }
        }

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

        private void LoadCommandExecuted(object obj)
        {
            _ = InitBooksCollectionAsync();
        }

        private ICommand exportSelectedDataCommand;
        public ICommand ExportSelectedDataCommand
        {
            get
            {
                if(exportSelectedDataCommand==null)
                {
                    exportSelectedDataCommand = new DelegateCommand(ExportSelectedDataCommandExecuted);
                }
                return exportSelectedDataCommand;
            }
        }

        private void ExportSelectedDataCommandExecuted(object obj)
        {
            var items = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
            if(items!=null && items.Any())
            {
                string jsonStr = JsonConvert.SerializeObject(items, Formatting.Indented);
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Filter = "Json Files|*.json|All Files|*.*";
                dlg.FileName = $"Json_{GetTimeNow()}.json";
                if (dlg.ShowDialog() == true)
                {
                    using (StreamWriter jsonWriter = new StreamWriter(dlg.FileName, false, System.Text.Encoding.UTF8))
                    {
                        jsonWriter.WriteLine(jsonStr);
                        tempMsg = $"{GetTimeNow()},export {items.Count} items to {dlg.FileName}";
                        SetMainTitle(tempMsg);
                        MessageBox.Show(tempMsg);
                    }
                }
            }           
        }

        private void SetMainTitle(string msg)
        {
            Application.Current?.Dispatcher.Invoke(() =>
            {
                MainTitle = msg;
            }, System.Windows.Threading.DispatcherPriority.Background);
        }

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

        private string mainTitle;
        public string MainTitle
        {
            get
            {
                return mainTitle;
            }
            set
            {
                if (value != mainTitle)
                {
                    mainTitle = value;
                    OnPropertyChanged();
                }
            }
        }

        private string GetTimeNow()
        {
            return $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}";
        }

        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 Book
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string CategoryName { get; set; }
        public string ISBN { get; set; }
        public string Comment { get; set; }
        public string Summary { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
    }

    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 RaiseCanExecuted()
        {

        }
    }
}

//WCF

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService2
{
    // 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}",
            RequestFormat =WebMessageFormat.Json,
            ResponseFormat =WebMessageFormat.Json)]
        List<Book> GetBooks(int cnt = 100);
    }


    public class Book
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string CategoryName { get; set; }
        public string ISBN { get; set; }
        public string Comment { 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 WcfService2
{
    // 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 string[] enumNames = Enum.GetNames(typeof(BookCategory));
        private static int enumsLen = enumNames.Length;
        private static Random rnd = new Random();
        private static long id = 1;
        private static (long, long) GetStartEnd(int cnt = 1000)
        {
            long end = Interlocked.Add(ref id, cnt);
            long start = end - cnt;
            return (start, end);
        }


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


<?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"
                         openTimeout="01:00:00"
                         closeTimeout="01:00:00"
                         sendTimeout="01:00:00"
                         receiveTimeout="01:00:00"
                         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="WcfService2.BookService"
                     behaviorConfiguration="BookServiceBehavior">
                <endpoint address=""
                          binding="webHttpBinding"
                          contract="WcfService2.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>

image

image

image

image

image