WPF ItemsControl load data from WCF,DataTemplate, ContentControl

<Window x:Class="WpfApp3.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:WpfApp3"
        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="BookRowDataTemplate">
            <Border BorderBrush="LightGray" 
                    BorderThickness="2"
                    Margin="10">

                <Grid Margin="5">
                    <Grid.Resources>
                        <Style TargetType="TextBlock" BasedOn="{StaticResource TbkStyle}"/>
                    </Grid.Resources>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Id}"/>
                    <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Name}"/>
                    <TextBlock Grid.Row="0" Grid.Column="2" Text="{Binding CategoryName}"/>
                    <TextBlock Grid.Row="1" Grid.Column="0" Text="{Binding Comment}"/>
                    <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Summary}"/>
                    <TextBlock Grid.Row="1" Grid.Column="2" Text="{Binding Title}"/>
                    <TextBlock Grid.Row="2" Grid.Column="0" Text="{Binding Topic}"/>
                    <TextBlock Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding ISBN}"/>
                </Grid>
            </Border>
        </DataTemplate>

        <ControlTemplate  TargetType="ContentControl" x:Key="BookControlTemplate">
            <ScrollViewer>
                <ItemsControl ItemsSource="{Binding BksCollection}"
               ItemTemplate="{StaticResource BookRowDataTemplate}">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <VirtualizingStackPanel IsItemsHost="True"/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.ContextMenu>
                        <ContextMenu>
                            <MenuItem Header="Load Data"
                                      Width="300"
                                      FontSize="30"
                                      Command="{Binding LoadCommand}"/>
                        </ContextMenu>
                    </ItemsControl.ContextMenu>
                </ItemsControl>
            </ScrollViewer>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <ContentControl Template="{StaticResource BookControlTemplate}"/>
    </Grid>
</Window>


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

namespace WpfApp3
{
    /// <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;
        public MainVM()
        {
            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                _ = InitBooksAsync(10000);
            }
        }

        private async Task InitBooksAsync(int cnt = 10000)
        {
            if(isLoading)
            {
                return;
            }
            isLoading = true;

            try
            {
                string url = $"{originUrl}{cnt}";
                string xmlStr = await client.GetStringAsync(url);
                var bksList = ConvertXmlStrToList(xmlStr);
                BksCollection = new ObservableCollection<Book>(bksList);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex?.Message);
            }
            finally
            {
                isLoading = false;
            }           
        }

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

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

        private void LoadCommandExecuted(object? obj)
        {
            _ = InitBooksAsync(10000);
        }

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

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

    [XmlRoot("ArrayOfBook", Namespace = "http://schemas.datacontract.org/2004/07/WcfService2")]
    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 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 ?? throw new ArgumentNullException(nameof(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.BeginInvoke(() =>
                    {
                        handler(this, EventArgs.Empty);
                    });
                }
            }
        }
    }
}

 

 

//WCF

using System;
using System.Collections.Generic;
using System.Linq;
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}")]
        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

 

posted @ 2026-08-23 20:14  FredGrit  阅读(0)  评论(0)    收藏  举报