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

 更新时间:2017年10月10日 14:52:17   作者:秋荷雨翔  
这篇文章主要为大家详细介绍了WPF自定义选择年月控件的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了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;
      }
    }
  }
}


效果图:

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

相关文章

  • C#中var关键字用法分析

    C#中var关键字用法分析

    这篇文章主要介绍了C#中var关键字用法,实例分析了C#中var关键字的应用场合,对于.NET的学习具有一定参考价值,需要的朋友可以参考下
    2014-12-12
  • C# SMTP发送邮件的示例

    C# SMTP发送邮件的示例

    这篇文章主要介绍了C# SMTP发送邮件的示例,帮助大家更好的理解和学习c#,感兴趣的朋友可以了解下
    2020-12-12
  • 浅析C#中静态方法和非静态方法的区别

    浅析C#中静态方法和非静态方法的区别

    C#静态方法与非静态方法的区别不仅仅是概念上的,那么他们有什么具体的区别呢?让我们通过本文向大家介绍下C#中静态方法和非静态方法的区别,一起看看吧
    2017-09-09
  • C#设计模式编程中运用适配器模式结构实战演练

    C#设计模式编程中运用适配器模式结构实战演练

    这篇文章主要介绍了C#设计模式编程中运用适配器模式结构实战演练,并总结了适配器模式的优缺点和适用场景以及.NET框架中的应用,需要的朋友可以参考下
    2016-02-02
  • WPF自定义选择年月控件详解

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

    这篇文章主要为大家详细介绍了WPF自定义选择年月控件的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-10-10
  • Unity UGUI实现卡片椭圆方向滚动

    Unity UGUI实现卡片椭圆方向滚动

    这篇文章主要为大家详细介绍了UGUI实现卡片椭圆方向滚动效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-03-03
  • 基于mvc5+ef6+Bootstrap框架实现身份验证和权限管理

    基于mvc5+ef6+Bootstrap框架实现身份验证和权限管理

    最近刚做完一个项目,项目架构师使用mvc5+ef6+Bootstrap,用的是vs2015,数据库是sql server2014。下面小编把mvc5+ef6+Bootstrap项目心得之身份验证和权限管理模块的实现思路分享给大家,需要的朋友可以参考下
    2016-06-06
  • Netcore Webapi返回数据的三种方式示例

    Netcore Webapi返回数据的三种方式示例

    这篇文章主要为大家介绍了Netcore Webapi返回数据的三种方式示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • c#使用IMap收取163邮件的方法示例

    c#使用IMap收取163邮件的方法示例

    大家都知道,设置IMAP服务后,不论是在客户端、手机、iPad还是网页中,发送邮件、阅读邮件后在各处均可以同步显示。下面这篇文章主要介绍了c#使用IMap收取163邮件的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下。
    2018-02-02
  • 深入理解C#指针之美

    深入理解C#指针之美

    在C#中,有时候希望通过指针来操作内存,这样可以提高效率。我们可以用unsafe关键字修饰含有指针操作的程序段,感兴趣的小伙伴可以参考一下,希望可以帮到你
    2021-07-07

最新评论