WPF ListBox load data from WCF

 
<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"
        Title="{Binding MainTitle}"
        WindowState="Maximized">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Window.Resources>
        <local:LenConverter x:Key="LenConverter"/>

        <ControlTemplate TargetType="ContentControl" x:Key="LbxControlTemplate">
            <ListBox ItemsSource="{Binding BksCollection}"
                     VirtualizingPanel.IsVirtualizing="True"
                     VirtualizingPanel.VirtualizationMode="Recycling"
                     VirtualizingPanel.CacheLengthUnit="Item"
                     VirtualizingPanel.CacheLength="3,3"
                     SnapsToDevicePixels="True"
                     UseLayoutRounding="True">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Grid Margin="10"
                              Width="{Binding Source={x:Static SystemParameters.FullPrimaryScreenWidth},
                            Converter={StaticResource LenConverter},ConverterParameter=1}"
                              Height="{Binding Source={x:Static SystemParameters.FullPrimaryScreenHeight},
                            Converter={StaticResource LenConverter},ConverterParameter=4}">
                            <Grid.Resources>
                                <Style TargetType="TextBlock">
                                    <Setter Property="FontSize" Value="30"/>
                                    <Setter Property="FontWeight" Value="Normal"/>
                                    <Style.Triggers>
                                        <Trigger Property="IsMouseOver" Value="True">
                                            <Setter Property="FontWeight" Value="ExtraBold"/>
                                            <Setter Property="Foreground" Value="Red"/>
                                        </Trigger>
                                    </Style.Triggers>
                                </Style>
                            </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>
                    </DataTemplate>
                </ListBox.ItemTemplate>
                <ListBox.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Load Data"
                                  FontSize="30"
                                  Width="300"
                                  Command="{Binding LoadDataCommand}"/>
                    </ContextMenu>
                </ListBox.ContextMenu>
            </ListBox>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <ContentControl Template="{StaticResource LbxControlTemplate}"/>
    </Grid>
</Window>


using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
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 Newtonsoft.Json;

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

    public class MainVM : INotifyPropertyChanged
    {
        private bool isLoading = false;
        private static HttpClient httpClient = new HttpClient()
        {
            Timeout = TimeSpan.FromHours(1)
        };

        private static string originUrl = "http://localhost:59166/BookService.svc/getbooks?cnt=";
        private static string msg = "";

        public MainVM()
        {
            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                MainTitle = GetTimeNow();
                _ = InitBksCollectionAsync();
            }
        }

        private async Task InitBksCollectionAsync(int cnt = 3000000)
        {
            if (isLoading)
            {
                return;
            }
            isLoading = true;
            MainTitle = $"{GetTimeNow()},loading...";
            try
            {
                string url = $"{originUrl}{cnt}";
                string jsonStr = await httpClient.GetStringAsync(url);
                List<Book> bksList = JsonConvert.DeserializeObject<List<Book>>(jsonStr);
                BksCollection = new ObservableCollection<Book>(bksList);
                MainTitle = $"{GetTimeNow()},FirstId:{BksCollection.FirstOrDefault()?.Id}," +
                    $"LastId:{BksCollection.LastOrDefault()?.Id}";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex?.Message);
            }
            finally
            {
                isLoading = false;
            }
        }

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

        private void LoadDataCommandExecuted(object? obj)
        {
            _ = InitBksCollectionAsync();
        }

        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 propertyName = "")
        {
            var handler = Volatile.Read(ref PropertyChanged);
            if (handler == null)
            {
                return;
            }
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class LenConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if(double.TryParse(value?.ToString(),out double d1)
                && double.TryParse(parameter?.ToString(),out double d2)
                && d2>0)
            {
                return d1 / d2;
            }
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

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

 

 

 

 

 

 

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

 

posted @ 2026-08-23 21:45  FredGrit  阅读(2)  评论(0)    收藏  举报