服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - WPF自定义选择年月控件详解

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

2022-01-24 13:37秋荷雨翔 C#

这篇文章主要为大家详细介绍了WPF自定义选择年月控件的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<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>

后台代码:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
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自定义选择年月控件详解

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

原文链接:http://www.cnblogs.com/s0611163/p/7573774.html

延伸 · 阅读

精彩推荐
  • C#C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    这篇文章主要介绍了C#实现的文件操作封装类,结合完整实例形式分析了C#封装文件的删除,移动,复制,重命名等操作相关实现技巧,需要的朋友可以参考下...

    Rising_Sun3892021-12-28
  • C#c#学习之30分钟学会XAML

    c#学习之30分钟学会XAML

    一个界面程序的核心,无疑就是界面和后台代码,而xaml就是微软为构建应用程序界面而创建的一种描述性语言,也就是说,这东西是搞界面的...

    C#教程网8812021-12-10
  • C#C#基础之泛型

    C#基础之泛型

    泛型是 2.0 版 C# 语言和公共语言运行库 (CLR) 中的一个新功能。接下来通过本文给大家介绍c#基础之泛型,感兴趣的朋友一起学习吧...

    方小白7732021-12-03
  • C#C# 后台处理图片的几种方法

    C# 后台处理图片的几种方法

    本篇文章主要介绍了C# 后台处理图片的几种方法,非常具有实用价值,需要的朋友可以参考下。...

    IT小伙儿10162021-12-08
  • C#聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题,新手速来围观,一个通俗易懂的例子帮助大家更好的理解C#接口问题,感兴趣的小伙伴们可以参考一下...

    zenkey7072021-12-03
  • C#浅谈C# winForm 窗体闪烁的问题

    浅谈C# winForm 窗体闪烁的问题

    下面小编就为大家带来一篇浅谈C# winForm 窗体闪烁的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    C#教程网7962021-12-21
  • C#Unity3D UGUI实现缩放循环拖动卡牌展示效果

    Unity3D UGUI实现缩放循环拖动卡牌展示效果

    这篇文章主要为大家详细介绍了Unity3D UGUI实现缩放循环拖动展示卡牌效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参...

    诗远3662022-03-11
  • C#C#直线的最小二乘法线性回归运算实例

    C#直线的最小二乘法线性回归运算实例

    这篇文章主要介绍了C#直线的最小二乘法线性回归运算方法,实例分析了给定一组点,用最小二乘法进行线性回归运算的实现技巧,具有一定参考借鉴价值,需要...

    北风其凉8912021-10-18