WPF ContentPresenter ContentTemplate changes based on binded value via DataTrigger synchronously

Get-Project -All|Install-Package Newtonsoft.json

 

 <ContentPresenter Grid.Row="1" Content="{Binding}">
     <ContentPresenter.Style>
         <Style TargetType="ContentPresenter">
             <Setter Property="ContentTemplate" Value="{StaticResource ItemsControlDataTemplate}"/>
             <Style.Triggers>
                 <DataTrigger Binding="{Binding SelectedDataControl}" Value="{x:Static local:DataControlEnum.DataGrid}">
                     <Setter Property="ContentTemplate" Value="{StaticResource DataGridDataTemplate}"/>
                 </DataTrigger>
                 <DataTrigger Binding="{Binding SelectedDataControl}" Value="{x:Static local:DataControlEnum.ListBox}">
                     <Setter Property="ContentTemplate" Value="{StaticResource ListBoxTemplate}"/>
                 </DataTrigger>
             </Style.Triggers>
         </Style>
     </ContentPresenter.Style>
 </ContentPresenter>

 

 

<Window x:Class="WpfApp10.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:WpfApp10"
        mc:Ignorable="d"
        Title="{Binding MainTitle}" WindowState="Maximized">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Window.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="FontSize" Value="30"/>
            <Setter Property="FontWeight" Value="SemiBold"/>
            <Setter Property="Margin" Value="20,0"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Foreground" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>

        <Style TargetType="ComboBox">
            <Setter Property="FontSize" Value="30"/>
            <Setter Property="Margin" Value="5,2"/>
            <Setter Property="Width" Value="300"/>
        </Style>

        <DataTemplate DataType="{x:Type local:Book}" x:Key="BookDataTemplate">
            <Border BorderBrush="Cyan"
                    BorderThickness="2"
                    Margin="5">
                <Grid Margin="5">
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" MinWidth="350"/>
                        <ColumnDefinition Width="Auto" MinWidth="350"/>
                        <ColumnDefinition Width="*" MinWidth="500"/>
                    </Grid.ColumnDefinitions>
                    <Grid.Resources>
                        <Style TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}"/>
                    </Grid.Resources>
                    <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 ISBN}"/>
                    <TextBlock Grid.Row="1" Grid.Column="0" Text="{Binding Author}"/>
                    <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Comment}"/>
                    <TextBlock Grid.Row="1" Grid.Column="2" Text="{Binding Content}"/>
                    <TextBlock Grid.Row="2" Grid.Column="0" Text="{Binding Summary}"/>
                    <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Title}"/>
                    <TextBlock Grid.Row="2" Grid.Column="2" Text="{Binding Topic}"/>
                </Grid>
            </Border>
        </DataTemplate>

        <DataTemplate x:Key="ItemsControlDataTemplate">
            <ItemsControl ItemsSource="{Binding BksCollection}"
                          ItemTemplate="{StaticResource BookDataTemplate}"
                          BorderBrush="Blue"
                          BorderThickness="2"
                          Margin="10,5"
                          ScrollViewer.CanContentScroll="True"
                          ScrollViewer.IsDeferredScrollingEnabled="True">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <VirtualizingStackPanel ScrollViewer.IsDeferredScrollingEnabled="True"
                                                ScrollViewer.CanContentScroll="True"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.Template>
                    <ControlTemplate>
                        <Border BorderBrush="{TemplateBinding BorderBrush}"
                                BorderThickness="{TemplateBinding BorderThickness}">
                            <ScrollViewer CanContentScroll="True">
                                <ItemsPresenter HorizontalAlignment="Stretch"/>
                            </ScrollViewer>
                        </Border>
                    </ControlTemplate>
                </ItemsControl.Template>
                <ItemsControl.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Reload Data"  Width="350" FontSize="30"
                                      Command="{Binding ReloadDataCommand}"/>
                    </ContextMenu>
                </ItemsControl.ContextMenu>
            </ItemsControl>
        </DataTemplate>

        <DataTemplate x:Key="DataGridDataTemplate">
            <DataGrid ItemsSource="{Binding BksCollection}"
                      BorderBrush="Red"
                      BorderThickness="2"
                      Margin="10,5"
                      IsReadOnly="True"
                      SelectionMode="Extended"
                      VirtualizingPanel.IsVirtualizing="True"
                      VirtualizingPanel.VirtualizationMode="Recycling"
                      VirtualizingPanel.CacheLength="5,5"
                      VirtualizingPanel.CacheLengthUnit="Item"
                      ScrollViewer.CanContentScroll="True"
                      ScrollViewer.IsDeferredScrollingEnabled="True"
                      UseLayoutRounding="True"
                      AutoGenerateColumns="False"
                      CanUserAddRows="False"
                      HeadersVisibility="Column">
                <DataGrid.Columns>
                    <DataGridTemplateColumn>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ContentPresenter Content="{Binding}"
                                                  ContentTemplate="{StaticResource BookDataTemplate}"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
                <DataGrid.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Reload Data"  Width="350" FontSize="30"
                                  Command="{Binding ReloadDataCommand}"/>
                    </ContextMenu>
                </DataGrid.ContextMenu>
            </DataGrid>
        </DataTemplate>

        <DataTemplate x:Key="ListBoxTemplate">
            <ListBox ItemsSource="{Binding BksCollection}"
                     ItemTemplate="{StaticResource BookDataTemplate}"
                     BorderBrush="Green"
                     BorderThickness="2"
                     Margin="10"
                     VirtualizingPanel.IsVirtualizing="True"
                     VirtualizingPanel.VirtualizationMode="Recycling"
                     VirtualizingPanel.CacheLength="5,5"
                     VirtualizingPanel.CacheLengthUnit="Item"
                     ScrollViewer.CanContentScroll="True"
                     ScrollViewer.IsDeferredScrollingEnabled="True">
                <ListBox.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Reload Data"  Width="350" FontSize="30"
                                  Command="{Binding ReloadDataCommand}"/>
                    </ContextMenu>
                </ListBox.ContextMenu>
            </ListBox>
        </DataTemplate>

    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" MinHeight="35"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0" Orientation="Horizontal">
            <TextBlock Text="DataControl Type:" Margin="10,2"/>
            <ComboBox ItemsSource="{Binding DataControlsCollection}"
                      SelectedItem="{Binding SelectedDataControl}"/>
        </StackPanel>
        <ContentPresenter Grid.Row="1" Content="{Binding}">
            <ContentPresenter.Style>
                <Style TargetType="ContentPresenter">
                    <Setter Property="ContentTemplate" Value="{StaticResource ItemsControlDataTemplate}"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding SelectedDataControl}" Value="{x:Static local:DataControlEnum.DataGrid}">
                            <Setter Property="ContentTemplate" Value="{StaticResource DataGridDataTemplate}"/>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding SelectedDataControl}" Value="{x:Static local:DataControlEnum.ListBox}">
                            <Setter Property="ContentTemplate" Value="{StaticResource ListBoxTemplate}"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ContentPresenter.Style>
        </ContentPresenter>

    </Grid>
</Window>


using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Net.Http;
using System.Reflection.Metadata;
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 WpfApp10
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class MainVM : INotifyPropertyChanged
    {
        static string url = "http://172.16.107.152:5000/getbooks/1000000";
        static HttpClient client = new HttpClient()
        {
            Timeout = TimeSpan.FromMinutes(1)
        };

        static bool isLoading = false;

        public MainVM()
        {
            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                _ = GetDataAsync();
                DataControlsCollection = new ObservableCollection<DataControlEnum>(System.Enum.GetValues<DataControlEnum>());
            }
        }

        private async Task GetDataAsync()
        {
            if (isLoading)
            {
                return;
            }
            isLoading = true;

            try
            {
                MainTitle = $"{DateTime.Now},loading...";
                var jsonStr = await client.GetStringAsync(url);
                if (!string.IsNullOrWhiteSpace(jsonStr))
                {
                    var bks = JsonConvert.DeserializeObject<List<Book>>(jsonStr);
                    if (bks != null && bks.Any())
                    {
                        BksCollection = new ObservableCollection<Book>(bks);
                        MainTitle = $"{DateTime.Now},FirstId:{BksCollection.FirstOrDefault()?.Id}," +
                            $"LastId:{BksCollection.LastOrDefault()?.Id}";
                        SelectedDataControl = DataControlEnum.ItemsControl;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex?.Message);
            }
            finally
            {
                isLoading = false;
            }
        }

        private ICommand reloadDataCommand;
        public ICommand ReloadDataCommand
        {
            get
            {
                if(reloadDataCommand==null)
                {
                    reloadDataCommand = new DelegateCommand(ReloadDataCommandExecuted);
                }
                return reloadDataCommand;
            }
        }

        private void ReloadDataCommandExecuted(object? obj)
        {
            _ = GetDataAsync();
        }

        private DataControlEnum selectedDataControl = DataControlEnum.ItemsControl;
        public DataControlEnum SelectedDataControl
        {
            get
            {
                return selectedDataControl;
            }
            set
            {
                if (value != selectedDataControl)
                {
                    selectedDataControl = value;
                    OnPropertyChanged();
                    OnSelectedDataControlChanged();
                }
            }
        }

        private void OnSelectedDataControlChanged()
        {
            MainTitle = $"{DateTime.Now},selected data control:{System.Enum.GetName(typeof(DataControlEnum),SelectedDataControl)}";
        }

        private ObservableCollection<DataControlEnum> dataControlsCollection;
        public ObservableCollection<DataControlEnum> DataControlsCollection
        {
            get
            {
                return dataControlsCollection;
            }
            set
            {
                if (value != dataControlsCollection)
                {
                    dataControlsCollection = 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;
        public void OnPropertyChanged([CallerMemberName] string propName = "")
        {
            var handler = Volatile.Read(ref PropertyChanged);
            if (handler != null)
            {
                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 Comment { get; set; }
        public string Content { get; set; }
        public string Summary { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
        public BookCategory CategoryName { get; set; }
    }

    public enum BookCategory
    {
        Science = 1,
        Technology = 2,
        Engineering = 3,
        Math = 4
    }

    public enum DataControlEnum
    {
        ItemsControl = 10,
        DataGrid = 20,
        ListBox=30
    }

    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 dispacther = Application.Current?.Dispatcher;
            if (dispacther != null)
            {
                if(dispacther.CheckAccess())
                {
                    handler(this, EventArgs.Empty);
                }
                else
                {
                    dispacther.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

 

 

 

 

 

 

image

 

 

 

 

 

image

 

 

 

 

 

 

image

 

 

 

 

 

image

 

 

 

image

 

 

//WebAPI

//D:\C\WebApplication5\Models\Book.cs
namespace WebApplication5.Models
{
    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 Comment { get; set;  }
        public string Content { get; set;  }
        public string Summary { get; set;  }
        public string Title { get; set;  }
        public string Topic { get; set; }
        public BookCategory CategoryName { get; set;  }
    }

    public enum BookCategory
    {
        Science=1,
        Technology=2,
        Engineering=3,
        Math=4
    }
}


//D:\C\WebApplication5\Controllers\BooksController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApplication5.Models;

namespace WebApplication5.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BooksController : ControllerBase
    {
        private static long id = 1;
        private static (long, long) GetStartEnd(int cnt = 1000000)
        {
            var end = Interlocked.Add(ref id, cnt);
            var start = end - cnt;
            return (start, end);
        }

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

        private BookCategory GetCategory(long i)
        {
            BookCategory category = BookCategory.Science;
            long result = i % 4;
            switch (result)
            {
                case 0:
                    category = BookCategory.Science;
                    break;
                case 1:
                    category = BookCategory.Technology;
                    break;
                case 2:
                    category = BookCategory.Engineering;
                    break;
                case 3:
                    category = BookCategory.Math;
                    break;
            }
            return category;
        }
    }
}


//D:\C\WebApplication5\Program.cs


namespace WebApplication5
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            builder.WebHost.UseKestrel(x =>
            {
                x.ListenAnyIP(5000);
                x.ListenAnyIP(5001, o =>
                {
                    o.UseHttps();
                });
            });
            builder.Services.AddControllers();
            builder.Services.AddControllers().AddJsonOptions(o =>
            {
                o.JsonSerializerOptions.Converters.Add(
                    new System.Text.Json.Serialization.JsonStringEnumConverter());
            });
            // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
            builder.Services.AddOpenApi();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.MapOpenApi();
            }
            //app.UseHttpsRedirection();

            app.UseAuthorization();


            app.MapControllers();

            app.Run();
        }
    }
}

 

image

 

posted @ 2026-11-08 17:02  FredGrit  阅读(8)  评论(0)    收藏  举报