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

效果图:

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

(0)

相关推荐

  • C# WPF ListView控件的实例详解

    C# WPF ListView控件的实例详解 C#的WPF作为现在微软主流的桌面程序开发平台,相比过去的MFC时代,有了非常多的不同.本人刚从MFC平台转过来,以为可以轻松上手,哪知碰到了很多问题,十分不解.不得不乖乖回去看了本书,再继续回到边左边边学的路上.在这边也推荐<深入浅出WPF>这本书,拿来上手还是极好的. 由于WPF以数据驱动UI的设计理念,很多控件用起来都与之前平台的相差很多,ListView控件算是有代表性的,这是进化的成果.关于该控件的应该,很多参考了这篇博文,如觉本人记述不

  • WPF的ListView控件自定义布局用法实例

    本文实例讲述了WPF的ListView控件自定义布局用法.分享给大家供大家参考,具体如下: 概要: 以源码的形式贴出,免得忘记后,再到网上查资料.在VS2008+SP1环境下调试通过 引用的GrayscaleEffect模块,可根据参考资料<Grayscale Effect...>中的位置下载. 正文: 如何布局是在App.xaml中定义源码如下 <Application x:Class="CWebsSynAssistant.App" xmlns="http

  • 在WPF中动态加载XAML中的控件实例代码

    本文实例讲述了在WPF中动态加载XAML中的控件的方法.分享给大家供大家参考,具体如下: 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 S

  • WPF实现带全选复选框的列表控件

    本文将说明如何创建一个带全选复选框的列表控件.其效果如下图: 这个控件是由一个复选框(CheckBox)与一个 ListView 组合而成.它的操作逻辑: 当选中"全选"时,列表中所有的项目都会被选中:反之,取消选中"全选"时,所有项都会被取消勾选. 在列表中选中部分数据项目时,"全选"框会呈现不确定状态(Indetermine). 由此看出,"全选"复选框与列表项中的复选框达到了双向控制的效果. 其设计思路:首先,创建自定义

  • WPF中不规则窗体与WindowsFormsHost控件兼容问题的解决方法

    本文实例讲述了WPF中不规则窗体与WindowsFormsHost控件兼容问题的解决方法.分享给大家供大家参考.具体方法如下: 这里首先说明一下,有关WPF中不规则窗体与WindowsFormsHost控件不兼容的问题,网上给出的很多解决方案不能满足所有的情况,是有特定条件的,比如有一篇<WPF中不规则窗体与WebBrowser控件的兼容问题解决办法>(感兴趣的朋友可以自己百度一下这篇文章).该网友的解决办法也是别出心裁的,为什么这样说呢,他的webBrowser控件的是单独放在一个Form中

  • WPF中在摄像头视频上叠加控件的解决方案

    说道WPF想必有很多朋友跟小编一样不知道wpf是什么,今天小编就给大家简单普及下基本概念. WPF(Windows Presentation Foundation)是微软推出的基于Windows 的用户界面框架,属于.NET Framework 3.0的一部分.它提供了统一的编程模型.语言和框架,真正做到了分离界面设计人员与开发人员的工作:同时它提供了全新的多媒体交互用户图形界面. 一.视频呈现 前段时间,在一个wpf的项目中需要实时显示ip摄像头,对此的解决方案想必大家都应该知道很多.在win

  • WPF实现ScrollViewer滚动到指定控件处

    在前端 UI 开发中,有时,我们会遇到这样的需求:在一个 ScrollViewer 中有很多内容,而我们需要实现在执行某个操作后能够定位到其中指定的控件处:这很像在 HTML 页面中点击一个链接后定位到当前网页上的某个 anchor. 要实现它,首先我们需要看 ScrollViewer 为我们提供的 API,其中并没有类似于 ScrollToControl 这样的方法:在它的几个以 ScrollTo 开头的方法中,最合适的就是 ScrollToVerticalOffset 这个方法了,这个方法接

  • 超炫酷的WPF实现Loading控件效果

    Win8系统的Loading效果还是很不错的,网上也有人用CSS3等技术实现,研究了一下,并打算用WPF自定义一个Loading控件实现类似的效果,并可以让用户对Loading的颗粒(Particle)背景颜色进行自定义,话不多说,直接上代码: 1.用VS2012新建一个WPF的用户控件库项目WpfControlLibraryDemo,VS自动生成如下结构: 2.删除UserControl1.xaml,并新建一个Loading的CustomControl(不是UserControl),如下图所示

  • WPF图形解锁控件ScreenUnLock使用详解

    ScreenUnLock 与智能手机上的图案解锁功能一样.通过绘制图形达到解锁或记忆图形的目的. 本人突发奇想,把手机上的图形解锁功能移植到WPF中.也应用到了公司的项目中. 在创建ScreenUnLock之前,先来分析一下图形解锁的实现思路. 1.创建九宫格原点(或更多格子),每个点定义一个坐标值 2.提供图形解锁相关扩展属性和事件,方便调用者定义.比如:点和线的颜色(Color),操作模式(Check|Remember),验证正确的颜色(RightColor), 验证失败的颜色(ErrorC

  • WPF中引入WindowsForms控件的方法

    本文实例讲述了WPF中引入WindowsForms控件的方法.分享给大家供大家参考,具体如下: 环境: [1]WindowsXP with SP3 [2]VS2008 with SP1 正文: Step1:在现有工程中引入Windows Forms 鼠标右键[References]->选择[Add Reference]->[.NET]标签页 加入[WindowsFormsIntegration]和[System.Windows.Forms]两项 Step2:在XAML文件里加入 [S2-1]加

随机推荐