WPF自定义选择年月控件详解

 更新时间:2020年6月25日 11:18  点击:2164

本文实例为大家分享了WPF自定义选择年月控件的具体代码,供大家参考,具体内容如下

封装了一个选择年月的控件,XAML代码:

<UserControl x:Class="SunCreate.CombatPlatform.Client.DateMonthPicker"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Height="23" Loaded="UserControl_Loaded">
  <UserControl.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/SunCreate.CombatPlatform.Client.Resources;Component/Resource/DateTimePickerResource.xaml" />
      </ResourceDictionary.MergedDictionaries>
      <Style TargetType="ToggleButton" x:Key="stlToggleButton">
        <Setter Property="Foreground" Value="White"></Setter>
        <Setter Property="Template">
          <Setter.Value>
            <ControlTemplate>
              <Border x:Name="Back" Background="Transparent" BorderThickness="0" BorderBrush="Transparent">
                <Path Name="PathFill" Fill="#1b94e0" Width="8" Height="6" StrokeThickness="0" Data="M5,0 L10,10 L0,10 z" RenderTransformOrigin="0.5,0.5" Stretch="Fill">
                  <Path.RenderTransform>
                    <TransformGroup>
                      <ScaleTransform/>
                      <SkewTransform/>
                      <RotateTransform Angle="180"/>
                      <TranslateTransform/>
                    </TransformGroup>
                  </Path.RenderTransform>
                </Path>
              </Border>
              <ControlTemplate.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                  <Setter TargetName="PathFill" Property="Fill" Value="#1b94e0"></Setter>
                  <Setter TargetName="Back" Property="Background" Value="Transparent"></Setter>
                  <Setter TargetName="Back" Property="BorderBrush" Value="Transparent"></Setter>
                </Trigger>
              </ControlTemplate.Triggers>
            </ControlTemplate>
          </Setter.Value>
        </Setter>
      </Style>
      <Style TargetType="ComboBox" x:Key="stlComboBox">
        <Setter Property="SnapsToDevicePixels" Value="True"/>
        <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
        <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
        <Setter Property="ScrollViewer.CanContentScroll" Value="True"/>
        <Setter Property="HorizontalAlignment" Value="Left"></Setter>
        <Setter Property="Foreground" Value="Black"></Setter>
        <Setter Property="Height" Value="30"></Setter>
        <Setter Property="Margin" Value="0,0,0,0"></Setter>
        <Setter Property="Template">
          <Setter.Value>
            <ControlTemplate TargetType="ComboBox">
              <Grid>
                <Grid.Background>
                  <ImageBrush ImageSource="/SunCreate.CombatPlatform.Client.Resources;component/Image/Face/1比n人脸比对/输入框.png"/>
                </Grid.Background>
                <Grid.ColumnDefinitions>
                  <ColumnDefinition Width="0.7*"/>
                  <ColumnDefinition Width="0.3*" MaxWidth="30" MinWidth="18"/>
                </Grid.ColumnDefinitions>
                <TextBox Grid.Column="0" IsReadOnly="True" Foreground="#1ba4f6" BorderThickness="1" BorderBrush="Transparent" Text="{TemplateBinding Text}" Background="Transparent"></TextBox>
                <Border Grid.Column="0" BorderThickness="0" Background="Transparent">
                </Border>
                <Border Grid.Column="1" BorderThickness="0" CornerRadius="0,1,1,0" Background="Transparent">
                  <ToggleButton Style="{StaticResource stlToggleButton}" IsChecked="{Binding Path=IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" ClickMode="Press"></ToggleButton>
                </Border>
                <Popup IsOpen="{TemplateBinding IsDropDownOpen}" Placement="Bottom" x:Name="Popup" Focusable="False" AllowsTransparency="True" PopupAnimation="Slide">
                  <Border CornerRadius="1" MaxHeight="{TemplateBinding MaxDropDownHeight}" MinWidth="{TemplateBinding ActualWidth}" x:Name="DropDown" SnapsToDevicePixels="True" Background="Transparent">
                    <Border.Effect>
                      <DropShadowEffect Color="#1ba4f6" BlurRadius="2" ShadowDepth="0" Opacity="0.5"/>
                    </Border.Effect>
                    <ScrollViewer Margin="4,6,4,6" Style="{DynamicResource ScrollViewerStyle}" MaxHeight="{TemplateBinding MaxDropDownHeight}" SnapsToDevicePixels="True" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" CanContentScroll="True">
                      <!-- StackPanel 用于显示子级,方法是将 IsItemsHost 设置为 True -->
                      <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" Background="#1ba4f6"/>
                    </ScrollViewer>
                  </Border>
                </Popup>
              </Grid>
            </ControlTemplate>
          </Setter.Value>
        </Setter>
      </Style>
    </ResourceDictionary>
  </UserControl.Resources>
  <Grid>
    <StackPanel Orientation="Horizontal">
      <ComboBox Grid.Column ="2" Grid.Row="0" Name="cbYear" SelectionChanged="cbYear_SelectionChanged" SelectedValuePath="Text" DisplayMemberPath="Text" Height="25" Width="55" Style="{StaticResource stlComboBox}" VerticalAlignment ="Center" >
      </ComboBox>
      <TextBlock Text="年" Margin="5 0 5 0" VerticalAlignment="Center" Foreground="#1ba4f6" />
      <ComboBox Grid.Column ="2" Grid.Row="0" Name="cbMonth" SelectionChanged="cbMonth_SelectionChanged" SelectedValuePath="Text" DisplayMemberPath="Text" Height="25" Width="40" Style="{StaticResource stlComboBox}" VerticalAlignment ="Center" >
      </ComboBox>
      <TextBlock Text="月" Margin="5 0 5 0" VerticalAlignment="Center" Foreground="#1ba4f6" />
    </StackPanel>
  </Grid>
</UserControl>

后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
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.ComponentModel;

namespace SunCreate.CombatPlatform.Client
{
  /// <summary>
  /// 
  /// </summary>
  public partial class DateMonthPicker : UserControl, INotifyPropertyChanged
  {
    private DateTime _selectedMonth;
    public static DependencyProperty selectedTimeProperty;

    static DateMonthPicker()
    {
      selectedTimeProperty = DependencyProperty.Register("SelectedMonth", typeof(DateTime), typeof(DateMonthPicker), new PropertyMetadata(DateTime.Now, new PropertyChangedCallback(SelectedMonthChanged)));
    }

    public DateMonthPicker()
    {
      InitializeComponent();

      int currentYear = DateTime.Now.Year;
      int currentMonth = DateTime.Now.Month;
      List<object> yearList = new List<object>();
      for (int i = currentYear - 20; i <= currentYear; i++)
      {
        yearList.Add(new { Text = i.ToString() });
      }
      cbYear.ItemsSource = yearList;

      cbMonth.ItemsSource = new List<object>() { 
        new { Text = "1" },
        new { Text = "2" },
        new { Text = "3" },
        new { Text = "4" },
        new { Text = "5" },
        new { Text = "6" },
        new { Text = "7" },
        new { Text = "8" },
        new { Text = "9" },
        new { Text = "10" },
        new { Text = "11" },
        new { Text = "12" }};

      this._selectedMonth = DateTime.Now;
    }

    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
      cbYear.SelectedValue = _selectedMonth.Year.ToString();
      cbMonth.SelectedValue = _selectedMonth.Month.ToString();
    }

    private static void SelectedMonthChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
      (obj as DateMonthPicker).ChangeSelect(e.NewValue);
    }

    private void ChangeSelect(object value)
    {
      _selectedMonth = (DateTime)value;
      cbYear.SelectedValue = _selectedMonth.Year.ToString();
      cbMonth.SelectedValue = _selectedMonth.Month.ToString();
    }

    public DateTime SelectedMonth
    {
      get { return (DateTime)this.GetValue(DateMonthPicker.selectedTimeProperty); }
      set { this.SetValue(DateMonthPicker.selectedTimeProperty, value); }
    }

    public DateTime StartDay
    {
      get
      {
        return this._selectedMonth.AddDays(1 - this._selectedMonth.Day).Date;
      }
    }

    public DateTime EndDay
    {
      get
      {
        return this.StartDay.AddMonths(1).AddDays(-1);
      }
    }

    #region INotifyPropertyChanged 成员
    public event PropertyChangedEventHandler PropertyChanged;
    private void SendPropertyChanged(String propertyName)
    {
      if (PropertyChanged != null)
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    private void cbYear_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      ComboBox cb = sender as ComboBox;
      if (this._selectedMonth != DateTime.MinValue && cb.SelectedValue != null)
      {
        this._selectedMonth = new DateTime(Convert.ToInt32(cb.SelectedValue), this._selectedMonth.Month, 1);
        SelectedMonth = this._selectedMonth;
      }
    }

    private void cbMonth_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      ComboBox cb = sender as ComboBox;
      if (this._selectedMonth != DateTime.MinValue && cb.SelectedValue != null)
      {
        this._selectedMonth = new DateTime(this._selectedMonth.Year, Convert.ToInt32(cb.SelectedValue), 1);
        SelectedMonth = this._selectedMonth;
      }
    }
  }
}


效果图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持猪先飞。

[!--infotagslink--]

相关文章

  • c# WPF中通过双击编辑DataGrid中Cell的示例(附源码)

    这篇文章主要介绍了c# WPF中通过双击编辑DataGrid中Cell的示例(附源码),帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下...2021-03-03
  • WPF实现类似360安全卫士界面的程序源码分享

    最近在网上看到了新版的360安全卫士,感觉界面还不错,于是用WPF制作了一个,时间有限,一些具体的控件没有制作,用图片代替了。感兴趣的朋友一起跟着小编学习WPF实现类似360安全卫士界面的程序源码分享...2020-06-25
  • WPF仿三星手机充电界面实现代码

    这篇文章主要为大家详细介绍了WPF仿三星手机充电界面实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-25
  • C# WPF 通过委托实现多窗口间的传值的方法

    这篇文章主要介绍了C# WPF 通过委托实现多窗口间的传值的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • WPF TextBox实现按字节长度限制输入功能

    这篇文章主要为大家详细介绍了WPF TextBox实现按字节长度限制输入功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-25
  • C#中WPF使用多线程调用窗体组件的方法

    这篇文章主要介绍了C#中WPF使用多线程调用窗体组件的方法,涉及C#中多线程的使用技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • WPF InkCanvas绘制矩形和椭圆

    这篇文章主要为大家详细介绍了WPF InkCanvas绘制矩形和椭圆,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-25
  • WPF基础教程之形状画刷与变换详解

    这篇文章主要给大家介绍了关于WPF基础教程之形状画刷与变换的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
  • WPF如何自定义TabControl控件样式示例详解

    这篇文章主要给大家介绍了关于WPF如何自定义TabControl控件样式的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。...2020-06-25
  • 解析WPF实现音频文件循环顺序播放的解决方法

    本篇文章是对WPF实现音频文件循环顺序播放的方法进行了详细的分析介绍,需要的朋友参考下...2021-09-22
  • WPF水珠效果按钮组的实现教程

    下面小编就为大家分享一篇WPF水珠效果按钮组的实现教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-09-22
  • WPF实现转圈进度条效果

    这篇文章主要为大家详细介绍了WPF实现转圈进度条效果,如何设计自定义的绕圈进度条,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-22
  • 在Winform和WPF中注册全局快捷键实现思路及代码

    如果注册快捷键,RegisterHotKey中的fsModifiers参数为0,即None选项,一些安全软件会警报,可能因为这样就可以全局监听键盘而造成安全问题,感兴趣的你可以参考下本文...2020-06-25
  • WPF中自定义GridLengthAnimation

    这篇文章主要为大家详细介绍了WPF中自定义GridLengthAnimation的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-22
  • WPF/Silverlight实现图片局部放大的方法分析

    这篇文章主要介绍了WPF/Silverlight实现图片局部放大的方法,结合实例形式分析了WPF/Silverlight针对图片属性操作相关实现技巧,需要的朋友可以参考下...2020-06-25
  • WPF MVVM制作发送短信小按钮

    这篇文章主要为大家详细介绍了WPF MVVM发送短信小按钮的制作方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-25
  • WPF中窗体最大化问题的解决方法

    这篇文章主要给大家介绍了关于WPF中窗体最大化问题的解决方法,文中通过示例代码介绍的非常详细,对大家学习或者使用wpf具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
  • C# WPF 父控件通过使用可视化树找到子控件的示例代码

    这篇文章主要介绍了C# WPF 父控件通过使用可视化树找到子控件的示例代码,需要的朋友可以参考下...2020-06-25
  • WPF如何绘制光滑连续贝塞尔曲线示例代码

    贝塞尔曲线,又称贝兹曲线或贝济埃曲线,一般的矢量图形软件通过它来精确画出曲线,下面这篇文章主要给大家介绍了关于WPF如何绘制光滑连续贝塞尔曲线的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下。...2020-06-25
  • WPF的ListView控件自定义布局用法实例

    这篇文章主要介绍了WPF的ListView控件自定义布局的方法,结合实例形式分析了WPF中ListView控件的布局方法,需要的朋友可以参考下...2020-06-25