惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
IT之家
IT之家
美团技术团队
酷 壳 – CoolShell
酷 壳 – CoolShell
Y
Y Combinator Blog
T
Tailwind CSS Blog
D
Docker
博客园 - Franky
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Google DeepMind News
Google DeepMind News
腾讯CDC
Vercel News
Vercel News
Engineering at Meta
Engineering at Meta
U
Unit 42
The Cloudflare Blog
S
SegmentFault 最新的问题
WordPress大学
WordPress大学
爱范儿
爱范儿
Recent Announcements
Recent Announcements
博客园 - 聂微东
博客园 - 叶小钗
H
Help Net Security
MyScale Blog
MyScale Blog

博客园 - FredGrit

WPF customize via three combied custom controls WPF DataGrid DataGridTemplateColumn DataTemplate ContentPresenter ContentTemplate WPF Customcontrol NumUpDownScroller WPF HierarchicalDataTemplate customize via ToggleButton WPF DataGrid DataGridTemplateColumn DataTemplate call predefined DataTemplate via ContentPresenter and ContentTemplate WPF ListBox load data via contentcontrol an ItemTemplate WPF DataGrid load data from Asp.Net Core WebAPI WPF TreeView HierarchicalDataTemplate with grouped Data WPF display grouped data with GroupBox and ItemsControl WPF two listbox scroll syncchronously via behavior WPF invoke data from WebAPI,DataGridTemplate call pre defined DataTemplate via ContentPresenter WPF ListBox load data from WCF WPF datagrid load data from WCF via json, export selected items to json file WPF ItemsControl load data from WCF,DataTemplate, ContentControl WPF customize rotated wheel relentlessly via custom control WPF embed DataTemplate in HierchicalDataTemplate of TreeView WPF ContentControl, ItemsControl, ItemsPanelTemplate,VirtualizingStackPanel,convert xml string to List<T> WPF parse web.config recursively, TreeView and HierarchicalDataTemplate WPF Custom control in cs and Generic.xaml WPF ContextMenu independent visual tree resolved via Freezable implemented class WPF custom control GetTemplateChild vs FindName,NameScope separation between Logical Tree and Visual Tree, WPF ListBox ListView Datatemplate, parse xml to List via XmlSerializer and StringReader WPF TreeView HierarchicalDataTemplate, parse xml via traverse in XmlElement WPF parse xml via [XmRoot] and [XmlElement] attributes together, contentcontrol's template is ControlTemplate from Resources WPF ContentControl invoke Template from resource, reuse datatemplate WPF deserialize xml string as List via [XmlRoot] and [XmlElement] attribute WPF ContentControl Template WPF DatagridTemplate Binding DataTemplate WPF TreeView explicitly given key name to HierarchicalDataTemplate WPF, parse XMlDocument as List
WPF CustomControl override Template in Generic.xaml and i...
FredGrit · 2026-09-05 · via 博客园 - FredGrit
//D:\C\WpfApp10\Themes\Generic.xaml
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApp10">

    <Style TargetType="{x:Type local:DateTimePicker}"
           x:Key="DateTimePickerStyle1">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:DateTimePicker}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Width="500"
                            Height="500">
                        <StackPanel Orientation="Vertical">
                            <Calendar x:Name="PART_Calendar"
                                      SelectedDate="{Binding SelectedDate}">
                                <Calendar.LayoutTransform>
                                    <ScaleTransform ScaleX="1.5"
                                                    ScaleY="1.5"/>
                                </Calendar.LayoutTransform>
                            </Calendar>
                            <TextBlock x:Name="PART_DTTbk"
                                       Text="{Binding Path=SelectedDTStr,RelativeSource={RelativeSource AncestorType={x:Type local:DateTimePicker}}}"
                                       FontSize="20"
                                       HorizontalAlignment="Center"/>
                        </StackPanel>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <Style TargetType="{x:Type local:DateTimePicker}"
           x:Key="DateTimePickerStyle2">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:DateTimePicker}">
                    <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                            Width="500"
                            Height="500">
                        <StackPanel Orientation="Vertical">
                            <TextBlock x:Name="PART_DTTbk"
                                       Text="{Binding Path=SelectedDTStr,RelativeSource={RelativeSource AncestorType={x:Type local:DateTimePicker}}}"
                                       FontSize="20"
                                       HorizontalAlignment="Center"/>

                            <Calendar x:Name="PART_Calendar"
                                  SelectedDate="{Binding SelectedDate}">
                                <Calendar.LayoutTransform>
                                    <ScaleTransform ScaleX="1.5"
                                                ScaleY="1.5"/>
                                </Calendar.LayoutTransform>
                            </Calendar>
                        </StackPanel>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>


</ResourceDictionary>


//D:\C\WpfApp10\DateTimePicker.cs
using System;
using System.Collections.Generic;
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>
    /// Follow steps 1a or 1b and then 2 to use this custom control in a XAML file.
    ///
    /// Step 1a) Using this custom control in a XAML file that exists in the current project.
    /// Add this XmlNamespace attribute to the root element of the markup file where it is 
    /// to be used:
    ///
    ///     xmlns:MyNamespace="clr-namespace:WpfApp10"
    ///
    ///
    /// Step 1b) Using this custom control in a XAML file that exists in a different project.
    /// Add this XmlNamespace attribute to the root element of the markup file where it is 
    /// to be used:
    ///
    ///     xmlns:MyNamespace="clr-namespace:WpfApp10;assembly=WpfApp10"
    ///
    /// You will also need to add a project reference from the project where the XAML file lives
    /// to this project and Rebuild to avoid compilation errors:
    ///
    ///     Right click on the target project in the Solution Explorer and
    ///     "Add Reference"->"Projects"->[Browse to and select this project]
    ///
    ///
    /// Step 2)
    /// Go ahead and use your control in the XAML file.
    ///
    ///     <MyNamespace:DateTimePicker/>
    ///
    /// </summary>
    public class DateTimePicker : Control
    {
        private Calendar calendarDT;
        public Calendar CalendarDT
        {
            get
            {
                return calendarDT;
            }
            set
            {
                if (calendarDT != null)
                {
                    calendarDT.SelectedDatesChanged -= CalendarDT_SelectedDatesChanged;
                }

                calendarDT = value;
                if (calendarDT != null)
                {
                    calendarDT.SelectedDatesChanged += CalendarDT_SelectedDatesChanged;
                }
            }
        }

        private void CalendarDT_SelectedDatesChanged(object? sender, SelectionChangedEventArgs e)
        {
            var cal = sender as Calendar;
            if (cal != null)
            {
                SelectedDT = cal.SelectedDate;
                if (SelectedDT.HasValue)
                {
                    SelectedDTStr = SelectedDT.Value.ToString("yyyy-MM-dd: HH:mm:ss.ffff");
                }
            }
        }

        static DateTimePicker()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(DateTimePicker), new FrameworkPropertyMetadata(typeof(DateTimePicker)));
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            var _calend = GetTemplateChild("PART_Calendar") as Calendar;
            if (_calend != null)
            {
                CalendarDT = _calend;
            }
        }

        public DateTime? SelectedDT
        {
            get { return (DateTime?)GetValue(SelectedDTProperty); }
            set { SetValue(SelectedDTProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SelctedDT.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedDTProperty =
            DependencyProperty.Register(nameof(SelectedDT),
                typeof(DateTime?),
                typeof(DateTimePicker),
                new PropertyMetadata(DateTime.Now, OnSelctedDTChanged));

        private static void OnSelctedDTChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var dtPicker = d as DateTimePicker;
            if (dtPicker != null)
            {
                if (dtPicker.SelectedDT.HasValue)
                {
                    dtPicker.SelectedDTStr = dtPicker.SelectedDT.Value.ToString("yyyy-MM-dd:HH:mm:ss.ffff");
                }
            }
        }

        public string SelectedDTStr
        {
            get { return (string)GetValue(SelectedDTStrProperty); }
            set { SetValue(SelectedDTStrProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SelectedDTStr.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedDTStrProperty =
            DependencyProperty.Register(nameof(SelectedDTStr),
                typeof(string),
                typeof(DateTimePicker),
                new PropertyMetadata(string.Empty));



    }
}


//D:\C\WpfApp10\App.xaml
<Application x:Class="WpfApp10.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp10"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Themes/Generic.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>


//D:\C\WpfApp10\MainWindow.xaml
<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}" Height="450" Width="800">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <local:DateTimePicker
            Grid.Row="0"
            Grid.Column="0"
            Style="{StaticResource DateTimePickerStyle1}"
            SelectedDT="{Binding SelectedDT,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>

        <local:DateTimePicker 
            Grid.Row="0"
            Grid.Column="1"
            Style="{StaticResource DateTimePickerStyle2}"
            SelectedDT="{Binding SelectedDT2,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
    </Grid>
</Window>


//D:\C\WpfApp10\MainWindow.xaml.cs
using System.ComponentModel;
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
    {

        private string mainTitle;
        public string MainTitle
        {
            get
            {
                return mainTitle;
            }
            set
            {
                if (value != mainTitle)
                {
                    mainTitle = value;
                    OnPropertyChanged();
                }
            }
        }

        private DateTime? selectedDT2;
        public DateTime? SelectedDT2
        {
            get
            {
                return selectedDT2;
            }
            set
            {
                if (value != selectedDT2)
                {
                    selectedDT2 = value;
                    OnPropertyChanged();
                    if (SelectedDT2.HasValue)
                    {
                        MainTitle = $"DateTimePicker2,{SelectedDT2.Value.ToString("yyyy-MM-dd HH:mm:ss.ffff")}";
                    }
                }
            }
        }

        private DateTime? selectedDT;
        public DateTime? SelectedDT
        {
            get
            {
                return selectedDT;
            }
            set
            {
                if (value != selectedDT)
                {
                    selectedDT = value;
                    OnPropertyChanged();
                    if (SelectedDT.HasValue)
                    {
                        MainTitle = $"DateTimePicker1,{SelectedDT.Value.ToString("yyyy-MM-dd HH:mm:ss.ffff")}";
                    }
                }
            }
        }

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

image

image

image