WPF ContentControl, ItemsControl, ItemsPanelTemplate,VirtualizingStackPanel,convert xml string to List<T>
<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; } } }


//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>

浙公网安备 33010602011771号