WPF DataGrid DataGridTemplateColumn DataTemplate ContentPresenter ContentTemplate

Install-Package Newtonsoft.json

 

WPF

//D:\C\WpfApp11\MainWindow.xaml
<Window x:Class="WpfApp11.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:WpfApp11"
        mc:Ignorable="d"
        Title="{Binding MainTitle}" WindowState="Maximized">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>

    <Window.Resources>
        <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">
            <Grid Margin="10"
                  Width="{x:Static SystemParameters.PrimaryScreenWidth}">
                <Grid.Resources>
                    <Style TargetType="TextBlock" BasedOn="{StaticResource TbkStyle}"/>
                </Grid.Resources>
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition MaxWidth="300"/>
                    <ColumnDefinition MaxWidth="300"/>
                    <ColumnDefinition Width="*"/>
                </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 Comment}" Grid.Row="1" Grid.Column="0"/>
                <TextBlock Text="{Binding Content}" Grid.Row="1" Grid.Column="1"/>
                <TextBlock Text="{Binding Author}" 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"/>
            </Grid>
        </DataTemplate>

        <ControlTemplate TargetType="ContentControl"
                         x:Key="DGTemplate">
            <DataGrid ItemsSource="{Binding BksCollection}"
                      VirtualizingPanel.IsVirtualizing="True"
                      VirtualizingPanel.VirtualizationMode="Recycling"
                      VirtualizingPanel.CacheLengthUnit="Item"
                      VirtualizingPanel.CacheLength="5,5"
                      ScrollViewer.CanContentScroll="True"
                      ScrollViewer.IsDeferredScrollingEnabled="True"
                      SnapsToDevicePixels="True"
                      UseLayoutRounding="True"
                      AutoGenerateColumns="False"
                      CanUserAddRows="False">
                <DataGrid.Columns>
                    <DataGridTemplateColumn>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ContentPresenter ContentTemplate="{StaticResource BookDataTemplate}"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
                <DataGrid.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Load Data"
                                  Width="300"
                                  FontSize="50"
                                  Command="{Binding LoadDataCommand}"/>
                    </ContextMenu>
                </DataGrid.ContextMenu>
            </DataGrid>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <ContentControl Template="{StaticResource DGTemplate}"/>
    </Grid>
</Window>


//D:\C\WpfApp11\MainWindow.xaml.cs
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.ComponentModel;
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 WpfApp11
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class MainVM : INotifyPropertyChanged
    {
        private static string url = "https://localhost:5001/getbooks/";
        private static HttpClient client = new HttpClient()
        {
            Timeout = TimeSpan.FromHours(1)
        };

        private bool isLoading = false;

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

        private async Task AutoLoadBooksAsync(int cnt = 1000000)
        {
            while (true)
            {
                await InitBksCollectionAsync();
                await Task.Delay(5000);
            }
        }

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

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

        private async Task InitBksCollectionAsync(int cnt = 1000000)
        {
            if (isLoading)
            {
                return;
            }
            isLoading = true;

            MainTitle = $"{DateTime.Now},loading...";
            try
            {
                string jsonStr = await client.GetStringAsync($"{url}{cnt}");
                var bks = JsonConvert.DeserializeObject<List<Book>>(jsonStr);
                BksCollection = new ObservableCollection<Book>(bks);
                MainTitle = $"{DateTime.Now},loaded {BksCollection.Count} items," +
                    $"First Id:{BksCollection.FirstOrDefault()?.Id}," +
                    $"Last Id:{BksCollection.LastOrDefault()?.Id}";
                PrintMsg(msg: MainTitle);
            }
            catch (Exception? ex)
            {
                MessageBox.Show(ex?.Message);
            }
            finally
            {
                isLoading = false;
            }
        }

        private void PrintMsg(string msg)
        {
#if DEBUG
            System.Diagnostics.Debug.WriteLine(msg);
#else
            System.Diagnostics.Trace.WriteLine(msg);
#endif
        }

        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 ISBN { get; set; }
        public string Author { get; set; }
        public string CategoryName { 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; }
    }

    public class DelegateCommand : ICommand
    {
        private readonly Action<Object?> execute;
        private readonly Func<object?, bool> canExecute;

        public DelegateCommand(Action<Object?> executeValue, Func<object?, bool> canExecuteValue = null)
        {
            execute = executeValue;
            canExecute = canExecuteValue;
        }

        public event EventHandler? CanExecuteChanged;

        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 bool CanExecute(object? parameter)
        {
            return canExecute == null ? true : canExecute(parameter);
        }

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

 

 

 

 

 

 

 

image

 

 

 

 

image

 

posted @ 2026-09-06 12:58  FredGrit  阅读(4)  评论(0)    收藏  举报