欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-17 14:58:58
本文实例为大家分享了wpf自定义选择年月控件的具体代码,供大家参考,具体内容如下 封装了一个选择年月的控件,xaml代码:

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


效果图:

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

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

上一篇:

下一篇: