WPF ContentControl invoke Template from resource, reuse datatemplate

<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="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="RowDataTemplate">
            <Border BorderBrush="LightGray"
                    BorderThickness="1"
                    Margin="5">
                <Grid>
                    <Grid.Resources>
                        <Style TargetType="TextBlock" BasedOn="{StaticResource TbkStyle}"/>
                    </Grid.Resources>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <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="1" Grid.Column="0"/>
                    <TextBlock Text="{Binding Comment}" Grid.Row="1" Grid.Column="1"/>
                    <TextBlock Text="{Binding Content}" Grid.Row="2" Grid.Column="0"/>
                    <TextBlock Text="{Binding Summary}" Grid.Row="2" Grid.Column="1"/>
                    <TextBlock Text="{Binding Title}" Grid.Row="3" Grid.Column="0"/>
                    <TextBlock Text="{Binding Topic}" Grid.Row="3" Grid.Column="1"/>
                    <TextBlock Text="{Binding ISBN}" Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2"/>
                </Grid>
            </Border>
        </DataTemplate>

        <DataTemplate DataType="{x:Type local:GroupedBook}"
                      x:Key="GroupDataTemplate">
            <GroupBox Header="{Binding GroupName}"
                      FontSize="50"
                      FontWeight="ExtraBold"
                      BorderBrush="LightBlue"
                      BorderThickness="2"
                      Margin="5">
                <ItemsControl ItemsSource="{Binding Bks}"
                              ItemTemplate="{StaticResource RowDataTemplate}"
                              Margin="5"
                              VirtualizingPanel.IsVirtualizing="True"
                              VirtualizingPanel.VirtualizationMode="Recycling"
                              VirtualizingPanel.CacheLength="5,5"
                              VirtualizingPanel.CacheLengthUnit="Item"
                              UseLayoutRounding="True"
                              SnapsToDevicePixels="True"
                              ScrollViewer.CanContentScroll="True"
                              ScrollViewer.IsDeferredScrollingEnabled="True">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <VirtualizingStackPanel/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.Resources>
                        <Style TargetType="TextBlock" BasedOn="{StaticResource TbkStyle}"/>
                    </ItemsControl.Resources>
                </ItemsControl>
            </GroupBox>
        </DataTemplate>

        <ControlTemplate  TargetType="ContentControl" 
                          x:Key="ContentControlTemplate">
            <ScrollViewer>
                <ItemsControl ItemsSource="{Binding GroupedBks}"
                              ItemTemplate="{StaticResource GroupDataTemplate}"
                              VirtualizingPanel.IsVirtualizing="True"
                              VirtualizingPanel.VirtualizationMode="Recycling"
                              VirtualizingPanel.CacheLengthUnit="Item"
                              VirtualizingPanel.CacheLength="5,5"
                              ScrollViewer.CanContentScroll="True"
                              ScrollViewer.IsDeferredScrollingEnabled="True"
                              UseLayoutRounding="True"
                              SnapsToDevicePixels="True">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <VirtualizingStackPanel/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.ContextMenu>
                        <ContextMenu>
                            <MenuItem Header="Refresh"
                                      Command="{Binding RefreshDataCommad}"/>
                        </ContextMenu>
                    </ItemsControl.ContextMenu>
                </ItemsControl>
            </ScrollViewer>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <ContentControl Template="{StaticResource ContentControlTemplate}"/>
    </Grid>
</Window>



using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
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 WpfApp5
{
    /// <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.FromSeconds(120)
        };

        string serviceUrl = "http://localhost:56293/BookService.svc/getbooks?cnt=";
        private CancellationTokenSource _cts = new CancellationTokenSource();
        private Task _loadTask;

        public DelegateCommand RefreshDataCommad { get; }

        public MainVM()
        {
            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                _loadTask = LoadBooksAsync(10, _cts.Token);
                RefreshDataCommad = new DelegateCommand(RefreshDataCommadExecuted);
            }
        }

        private void RefreshDataCommadExecuted(object? obj)
        {
            //_ = LoadBooksAsync();
        }

        private async Task LoadBooksAsync(int cnt = 1000000, CancellationToken token = default)
        {
            if (_cts.IsCancellationRequested)
            {
                return;
            }
            string url = $"{serviceUrl}{cnt}";
            string xmlStr = await client.GetStringAsync(url);
            var bks = ParseXmlStr(xmlStr);
            var groups = bks.GroupBy(x => x.CategoryName);
            if (groups != null && groups.Any())
            {
                GroupedBks = new ObservableCollection<GroupedBook>();
                foreach (var g in groups)
                {
                    GroupedBks.Add(new GroupedBook()
                    {
                        GroupName = g.Key,
                        Bks = g.ToList()
                    });
                }
            }
        }

        private List<Book> ParseXmlStr(string xmlStr)
        {
            try
            {
                var serializer = new XmlSerializer(typeof(BookList));
                using (var reader = new StringReader(xmlStr))
                {
                    var bksList = serializer.Deserialize(reader) as BookList;
                    if (bksList != null)
                    {
                        return bksList.Bks;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex?.Message);
            }
            return null;
        }

        private ObservableCollection<GroupedBook> _groupedBks;
        public ObservableCollection<GroupedBook> GroupedBks
        {
            get
            {
                return _groupedBks;
            }
            set
            {
                if (value != _groupedBks)
                {
                    _groupedBks = value;
                    OnPropertyChanged();
                }
            }
        }

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

    public class GroupedBook
    {
        public string GroupName { get; set; }
        public List<Book> Bks { get; set; }
    }

    [XmlRoot("ArrayOfBook", Namespace = "http://schemas.datacontract.org/2004/07/WcfService2")]
    public class BookList
    {
        [XmlElement("Book")]
        public List<Book> Bks { get; set; }
    }

    public class Book
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string CategoryName { get; set; }
        public string Author { 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 DelegateCommand : ICommand
    {
        private readonly Action<object?> _execute;
        private Func<object?, bool>? _canExecute;
        public DelegateCommand(Action<object?> execute, Func<object?, bool>? canExecute = null)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
            _canExecute = canExecute;
        }

        public event EventHandler? CanExecuteChanged;

        public bool CanExecute(object? parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }

        public void Execute(object? parameter)
        {
            _execute?.Invoke(parameter);
        }

        public void RaiseCanExecutedChanged(object sender,EventArgs e)
        {
            var handler = Volatile.Read(ref CanExecuteChanged);
            if(handler==null)
            {
                return;
            }

            var dispacther = Application.Current?.Dispatcher;
            if(dispacther!=null)
            {
                if(dispacther.CheckAccess())
                {
                    handler.Invoke(this, e);
                }
                else
                {
                    dispacther.Invoke(() =>
                    {
                        handler.Invoke(this, e);
                    },System.Windows.Threading.DispatcherPriority.Background);
                }
            }
        }
    }
}

 

 

 

image

 

posted @ 2026-07-25 22:02  FredGrit  阅读(3)  评论(0)    收藏  举报