WPF ContentPresenter ContentTemplate changed based on another value

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 models:DataControlEnum.DataGrid}">
                     <Setter Property="ContentTemplate" Value="{StaticResource DataGridDataTemplate}"/>
                 </DataTrigger>
             </Style.Triggers>
         </Style>
     </ContentPresenter.Style>
 </ContentPresenter>

 

 

 

 

image

 

 

 

//D:\C\WpfApp9\Models\Book.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace WpfApp9.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\WpfApp9\Models\DataControlEnum.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace WpfApp9.Models
{
    public enum DataControlEnum
    {
        ItemsControl = 10,
        DataGrid = 20
    }
}


//D:\C\WpfApp9\Utility\DelegateCommand.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Input;

namespace WpfApp9.Utility
{
    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 ?? throw new ArgumentNullException(nameof(executeValue));
            canExecute = canExecuteValue;
        }

        public event EventHandler? CanExecuteChanged;
        public void RaiseCanExecuteChanged()
        {
            var handler = Volatile.Read(ref CanExecuteChanged);
            if (handler != null)
            {
                var dispatcher = System.Windows.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)
        {
            throw new NotImplementedException();
        }

        public void Execute(object? parameter)
        {
            throw new NotImplementedException();
        }
    }
}


//D:\C\WpfApp9\Utility\NotifyBase.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;

namespace WpfApp9.Utility
{
    public class NotifyBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;
        public void OnPropertyChanged([CallerMemberName] string propName="")
        {
            var handler=Volatile.Read(ref PropertyChanged);
            if(handler!=null)
            {
                handler(this, new PropertyChangedEventArgs(propName));
            }
        }
    }
}



//D:\C\WpfApp9\ViewModels\MainViewModel.cs
using Newtonsoft.Json;
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text;
using System.Windows;
using WpfApp9.Models;
using WpfApp9.Utility;

namespace WpfApp9.ViewModels
{
    public class MainViewModel: NotifyBase
    {
        static string url = "http://192.168.52.240:5000/getbooks/1000000";
        static HttpClient client = new HttpClient()
        {
            Timeout = TimeSpan.FromMinutes(1)
        };

        static bool isLoading = false;

        public MainViewModel()
        {
            if(!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                _ = LoadBooksAsync();
            }
        }

        private ObservableCollection<DataControlEnum> dataControlCollection;
        public ObservableCollection<DataControlEnum> DataControlCollection
        {
            get
            {
                return dataControlCollection;
            }
            set
            {
                if(value!=dataControlCollection)
                {
                    dataControlCollection = value;
                    OnPropertyChanged();
                }
            }
        }

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

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

            try
            {
                MainTitle = $"{DateTime.Now},loading...";
                string 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}";
                        DataControlCollection =new ObservableCollection<DataControlEnum>(System.Enum.GetValues<DataControlEnum>());
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex?.Message);
            }
            finally
            {
                isLoading = false;
            }
        }

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


//D:\C\WpfApp9\Views\MainView.xaml
<Window x:Class="WpfApp9.Views.MainView"
        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:WpfApp9.Views"
        xmlns:vm="clr-namespace:WpfApp9.ViewModels"
        xmlns:models="clr-namespace:WpfApp9.Models"
        xmlns:views="clr-namespace:WpfApp9.Views"
        mc:Ignorable="d"
        Title="{Binding MainTitle}" WindowState="Maximized">
    <Window.DataContext>
        <vm:MainViewModel/>
    </Window.DataContext>
    <Window.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="FontSize" Value="30"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="Margin" Value="3,0"/>
        </Style>

        <Style TargetType="ComboBox">
            <Setter Property="Height" Value="50"/>
            <Setter Property="FontSize" Value="30"/>
        </Style>

        <DataTemplate DataType="{x:Type models:Book}" x:Key="BookDataTemplate">
            <Grid Margin="5"
                  Width="{x:Static SystemParameters.FullPrimaryScreenWidth}">
                <Grid.Resources>
                    <Style TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}"/>
                </Grid.Resources>
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" MinWidth="200"/>
                    <ColumnDefinition Width="Auto" MinWidth="200"/>
                    <ColumnDefinition Width="*" MinWidth="200"/>
                </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 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>
        </DataTemplate>

        <DataTemplate x:Key="ItemsControlDataTemplate">
            <ItemsControl ItemsSource="{Binding BksCollection}"
                          ItemTemplate="{StaticResource BookDataTemplate}"
                          BorderBrush="Blue"
                          BorderThickness="5"
                          Margin="10">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <VirtualizingStackPanel ScrollViewer.CanContentScroll="True"
                                                ScrollViewer.IsDeferredScrollingEnabled="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>
        </DataTemplate>

        <DataTemplate x:Key="DataGridDataTemplate">
            <DataGrid ItemsSource="{Binding BksCollection}"
                      BorderBrush="Red"
                      BorderThickness="5"
                      Margin="10"
                      AutoGenerateColumns="False"
                      CanUserAddRows="False"
                      UseLayoutRounding="True"
                      VirtualizingPanel.IsVirtualizing="True"
                      VirtualizingPanel.VirtualizationMode="Recycling"
                      VirtualizingPanel.CacheLengthUnit="Item"
                      VirtualizingPanel.CacheLength="5,5"
                      ScrollViewer.CanContentScroll="True"
                      ScrollViewer.IsDeferredScrollingEnabled="True"
                      HeadersVisibility="Column">
                <DataGrid.Columns>
                    <DataGridTemplateColumn>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ContentPresenter Content="{Binding}"
                                                  ContentTemplate="{StaticResource BookDataTemplate}"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
            </DataGrid>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <StackPanel Grid.Row="0" Orientation="Horizontal">
            <TextBlock Text="Data Control:" Margin="20,0"/>
            <ComboBox ItemsSource="{Binding DataControlCollection}"
                      SelectedItem="{Binding SelectedDataControl}"
                      Width="200" Margin="20,0"/>
        </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 models:DataControlEnum.DataGrid}">
                            <Setter Property="ContentTemplate" Value="{StaticResource DataGridDataTemplate}"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ContentPresenter.Style>
        </ContentPresenter>
       
    </Grid>
</Window>


//D:\C\WpfApp9\App.xaml
<Application x:Class="WpfApp9.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp9"
             StartupUri="Views/MainView.xaml">
    <Application.Resources>
         
    </Application.Resources>
</Application>

 

 

 

 

 

 

 

image

 

 

 

 

 

image

 

 

 

 

image

 

posted @ 2026-11-07 21:54  FredGrit  阅读(6)  评论(0)    收藏  举报