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

推荐订阅源

Y
Y Combinator Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
V2EX
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
罗磊的独立博客
博客园_首页
量子位
雷峰网
雷峰网
GbyAI
GbyAI
小众软件
小众软件
酷 壳 – CoolShell
酷 壳 – CoolShell
D
DataBreaches.Net
H
Hackread – Cybersecurity News, Data Breaches, AI and More
The Cloudflare Blog
IT之家
IT之家
WordPress大学
WordPress大学
人人都是产品经理
人人都是产品经理
Apple Machine Learning Research
Apple Machine Learning Research
P
Proofpoint News Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 聂微东

博客园 - 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 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 Data Source invoke from web api
FredGrit · 2026-03-15 · via 博客园 - FredGrit
Install-Package Newtonsoft.json
public async Task GetServiceDataAsync()
{
    string bookUrl = "https://localhost:7205/api/book";
    using (HttpClient hclient = new HttpClient())
    {
        var booksJson = await hclient.GetStringAsync(bookUrl);

        if (!string.IsNullOrWhiteSpace(booksJson))
        {
            List<Book>? booksList = JsonConvert.DeserializeObject<List<Book>>(booksJson);
            if (booksList != null && booksList.Any())
            {
                BooksCollection = new ObservableCollection<Book>(booksList);
            }
        }
    }
}
<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"
        WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Grid>
        <DataGrid ItemsSource="{Binding BooksCollection}"
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.VirtualizationMode="Recycling"
                  VirtualizingPanel.CacheLength="5,5"
                  VirtualizingPanel.CacheLengthUnit="Item"
                  AutoGenerateColumns="True"
                  CanUserAddRows="False"
                  EnableColumnVirtualization="True"
                  EnableRowVirtualization="True"
                  ScrollViewer.CanContentScroll="True"
                  ScrollViewer.IsDeferredScrollingEnabled="True"
                  SelectionMode="Extended">
            <DataGrid.RowStyle>
                <Style TargetType="DataGridRow">
                    <Setter Property="FontSize" Value="20"/>
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="FontSize" Value="25"/>
                            <Setter Property="Foreground" Value="Red"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.RowStyle>
            <DataGrid.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Export All As Json"
                              Command="{Binding ExportAllAsJsonCommand}"
                              CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},
                        Path=PlacementTarget.Items}"/>
                    <MenuItem Header="Export Selected As Json"
                              Command="{Binding ExportAsJsonCommand}"
                              CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},Path=PlacementTarget.SelectedItems}"/>
                </ContextMenu>
            </DataGrid.ContextMenu>
            
        </DataGrid>
    </Grid>
</Window>


using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Net;
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.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Newtonsoft.Json;

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

    public class MainVM : INotifyPropertyChanged
    {
        public MainVM()
        {
            GetServiceDataAsync();
        }



        public async Task GetServiceDataAsync()
        {
            string bookUrl = "https://localhost:7205/api/book";
            using (HttpClient hclient = new HttpClient())
            {
                var booksJson = await hclient.GetStringAsync(bookUrl);

                if (!string.IsNullOrWhiteSpace(booksJson))
                {
                    List<Book>? booksList = JsonConvert.DeserializeObject<List<Book>>(booksJson);
                    if (booksList != null && booksList.Any())
                    {
                        BooksCollection = new ObservableCollection<Book>(booksList);
                    }
                }
            }
        }

        private ICommand exportAsJsonCommand;
        public ICommand ExportAsJsonCommand
        {
            get
            {
                if (exportAsJsonCommand == null)
                {
                    exportAsJsonCommand = new DelCommand(ExportAsJsonCommandExecuted);
                }
                return exportAsJsonCommand;
            }
        }

        private ICommand exportAllAsJsonCommand;
        public ICommand ExportAllAsJsonCommand
        {
            get
            {
                if (exportAllAsJsonCommand == null)
                {
                    exportAllAsJsonCommand = new DelCommand(ExportAllAsJsonCommandExecuted);
                }
                return exportAllAsJsonCommand;
            }
        }

        private void ExportAllAsJsonCommandExecuted(object? obj)
        {
            var itemsList = ((System.Collections.IList)obj)?.Cast<Book>()?.ToList();
            if (itemsList != null && itemsList.Any())
            {
                string jsonStr = JsonConvert.SerializeObject(itemsList, Formatting.Indented);
                string jsonFile = $"JsonAll_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}";

                using (StreamWriter jsonWriter = new StreamWriter(jsonFile, false, Encoding.UTF8))
                {
                    jsonWriter.WriteLine(jsonStr);
                    MessageBox.Show($"Save json in {jsonFile}", $"{DateTime.Now}");
                }
            }
        }

        private void ExportAsJsonCommandExecuted(object? obj)
        {
            var bksList = ((System.Collections.IList)obj)?.Cast<Book>()?.ToList();
            if (bksList != null && bksList.Any())
            {
                string jsonStr = JsonConvert.SerializeObject(bksList, Formatting.Indented);
                string jsonFile = $"JsonSelected_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}";

                using (StreamWriter jsonWriter = new StreamWriter(jsonFile, false, Encoding.UTF8))
                {
                    jsonWriter.WriteLine(jsonStr);
                    MessageBox.Show($"Save json in {jsonFile}", $"{DateTime.Now}");
                }
            }
        }

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

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


    public class DelCommand : ICommand
    {
        private Action<object?>? execute;
        private Predicate<object?>? canExecute;
        public DelCommand(Action<object?>? executeValue, Predicate<object?>? canExecuteValue = null)
        {
            execute = executeValue;
            canExecute = canExecuteValue;
        }

        public event EventHandler? CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

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

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



    public class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string ISBN { get; set; }
        public string Author { get; set; }
        public string Abstract { 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; }
    }
}

image

image

posted @ 2026-03-15 00:42  FredGrit  阅读(5)  评论()    收藏  举报