WPF invoke data from WebAPI,DataGridTemplate call pre defined DataTemplate via ContentPresenter

//WebAPI
//D:\C\WebApplication1\WebApplication1\Book.cs
namespace WebApplication1
{
    public class Book
    {
        public long Id { get; set; }
        public string Name { get; set;  }
        public string Author { get; set; }
        public string CategoryName { get; set; }
        public string Comment { get; set; }
        public string Content { get; set; }
        public string ISBN { get; set;  }
        public string Summary { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
    }

    enum BookCategory
    {
        Science,Technology,Engineering,Math
    }
}


//D:\C\WebApplication1\WebApplication1\Controllers\BookController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BookController : ControllerBase
    {
        private static long id = 1;
        private static string[] enumNames = Enum.GetNames(typeof(BookCategory));
        private static int enumsLen = enumNames.Length;

        private static (long,long) GetStartEnd(int cnt)
        {
            long end=Interlocked.Add(ref id, cnt);
            long start = end - cnt;
            return(start,end);
        }

        [HttpGet("getbooks/{cnt}")]
        public List<Book> GetBooks(int cnt=1000)
        {
            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}",
                    ISBN=$"ISBN_{i}_{Guid.NewGuid():N}",
                    Comment=$"Comment_{i}",
                    Content=$"Content_{i}",
                    Summary=$"Summary_{i}",
                    CategoryName = $"{enumNames[i%enumsLen]}",
                    Author=$"Author_{i}",
                    Title=$"Title_{i}",
                    Topic=$"Topic_{i}"
                });
            }
            Console.WriteLine($"{DateTime.Now},Start:{start},End:{end}");
            return bksList;
        }
    }
}

 

 

 

 

<DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate >
                            <ContentPresenter Content="{Binding}"
                                              ContentTemplate="{StaticResource BookDataTemplate}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

 

 

 

 

//WPF
//D:\C\WpfApp1\WpfApp1\MainWindow.xaml
<Window x:Class="WpfApp1.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:WpfApp1"
        mc:Ignorable="d"
        Title="{Binding MainTitle}" WindowState="Maximized">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Window.Resources>
        <local:LenSubtractConverter x:Key="LenSubtractConverter"/>
        
        <Style TargetType="TextBlock" x:Key="TbkStyle">
            <Setter Property="FontSize" Value="30"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Foreground" Value="Red"/>
                    <Setter Property="FontWeight" Value="ExtraBold"/>
                </Trigger>
            </Style.Triggers>
        </Style>

        <DataTemplate DataType="{x:Type local:Book}"
                      x:Key="BookDataTemplate">
            <!--<Border BorderBrush="LightGray"
                    BorderThickness="3"
                    Margin="5">-->
                <Grid Margin="5"
                      Width="{Binding DataContext.WinContentWidth,RelativeSource={RelativeSource AncestorType=Window}}"                      
                      Height="{Binding Source={x:Static SystemParameters.FullPrimaryScreenHeight},
                      Converter={StaticResource LenSubtractConverter},ConverterParameter=5}">
                    <Grid.Resources>
                        <Style TargetType="TextBlock" BasedOn="{StaticResource TbkStyle}"/>
                    </Grid.Resources>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </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 Author}" Grid.Row="0" Grid.Column="2"/>
                    <TextBlock Text="{Binding CategoryName}" Grid.Row="1" Grid.Column="0"/>
                    <TextBlock Text="{Binding Comment}" Grid.Row="1" Grid.Column="1"/>
                    <TextBlock Text="{Binding Content}" Grid.Row="1" Grid.Column="2"/>
                    <TextBlock Text="{Binding Summary}" Grid.Row="2" Grid.Column="0"/>
                    <TextBlock Text="{Binding Title}" Grid.Row="2" Grid.Column="1"/>
                    <TextBlock Text="{Binding Topic}" Grid.Row="2" Grid.Column="2"/>
                    <TextBlock Text="{Binding ISBN}" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="3"/>
                </Grid>
            <!--</Border>-->
        </DataTemplate>

        <Style TargetType="DataGridRow">
            <Setter Property="FontSize" Value="30"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Foreground" Value="Red"/>
                    <Setter Property="FontWeight" Value="ExtraBold"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>        
        <DataGrid ItemsSource="{Binding BksCollection}"
                  RowDetailsTemplate="{StaticResource BookDataTemplate}"
                  AutoGenerateColumns="False"
                  CanUserAddRows="False"
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.VirtualizationMode="Recycling"
                  VirtualizingPanel.CacheLength="5,5"
                  VirtualizingPanel.CacheLengthUnit="Item"
                  ScrollViewer.CanContentScroll="True"
                  ScrollViewer.IsDeferredScrollingEnabled="True"
                  UseLayoutRounding="True"
                  SnapsToDevicePixels="True"
                  >
            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate >
                            <ContentPresenter Content="{Binding}"
                                              ContentTemplate="{StaticResource BookDataTemplate}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
            <DataGrid.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Load Data"
                              Width="300"
                              FontSize="30"
                              Command="{Binding LoadDataCommand}"/>
                </ContextMenu>
            </DataGrid.ContextMenu>
        </DataGrid>

    </Grid>
</Window>

//D:\C\WpfApp1\WpfApp1\MainWindow.xaml.cs

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

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private MainVM vm;
        public MainWindow()
        {
            InitializeComponent();

            this.SizeChanged += MainWindow_SizeChanged;
        }

        private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            var vm = this.DataContext as MainVM;
            if (vm != null)
            {
                var elem = this.Content as FrameworkElement;
                if (elem != null)
                {
                    var tempWidth = this.ActualWidth;
                    vm.WinContentWidth = elem.ActualWidth;
                }
            }
        }
    }

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

        static string url = "http://localhost:5000/api/book/getbooks/";
        private static bool isLoading = false;
        public MainVM()
        {
            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                _ = AutoLoadDataAsync(1000000);
            }
        }

        private async Task AutoLoadDataAsync(int cnt = 1000000)
        {
            while(true)
            {
                try
                {
                    await InitBooksAsync(cnt);
                    await Task.Delay(20000);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex?.Message);                     
                }
            }
        }

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

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

        private async Task InitBooksAsync(int cnt = 1000000)
        {
            if (isLoading)
            {
                return;
            }
            isLoading = true;
            MainTitle = $"{DateTime.Now},loading...";
            try
            {
                string jsonStr = await httpClient.GetStringAsync($"{url}{cnt}");
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    return;
                }

                var bks = JsonConvert.DeserializeObject<List<Book>>(jsonStr);
                BksCollection = new ObservableCollection<Book>(bks);
                MainTitle = $"{DateTime.Now},loaded {BksCollection.Count} items," +
                    $"FirstId:{BksCollection.FirstOrDefault()?.Id}," +
                    $"LastId:{BksCollection.LastOrDefault()?.Id}";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex?.Message);
            }
            finally
            {
                isLoading = false;
            }
        }

        private double winContentWidth = 0.0d;
        public double WinContentWidth
        {
            get
            {
                return winContentWidth;
            }
            set
            {
                if (value != winContentWidth)
                {
                    winContentWidth = value;
                    OnPropertyChanged();
                }
            }
        }

        private string mainTitle = $"{DateTime.Now}";
        public string MainTitle
        {
            get
            {
                return mainTitle;
            }
            set
            {
                if (value != mainTitle)
                {
                    mainTitle = value;
                    OnPropertyChanged();
                }
            }
        }

        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 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 Author { get; set; }
        public string CategoryName { get; set; }
        public string Comment { get; set; }
        public string Content { get; set; }
        public string ISBN { get; set; }
        public string Summary { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
    }

    public class LenSubtractConverter : 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 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);
        }
    }
}

 

 

image

 

 

 

 

image

 

 

 

 

image

 

 

image

 

posted @ 2026-08-30 15:55  FredGrit  阅读(8)  评论(0)    收藏  举报