wpf-datetime

日期选择控件

// 默认当前日期
xmlns:sys="clr-namespace:System;assembly=mscorlib"

/*
DatePicker.Resources 设置格式化
*/
<DatePicker Name="dp_start" Height="25" SelectedDate="{x:Static sys:DateTime.Now}" VerticalContentAlignment="Center">
<DatePicker.Resources>
<Style TargetType="{x:Type DatePickerTextBox}">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<TextBox x:Name="PART_TextBox"
Text="{Binding Path=SelectedDate, RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}, StringFormat={}{0:yyyy-MM-dd}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DatePicker.Resources>
</DatePicker>

日期时间控件

使用 nuget 安装 Extended.Wpf.Toolkit

xmlns:wpfTool="clr-namespace:Xceed.Wpf.Toolkit;assembly=Xceed.Wpf.Toolkit" 

dtp_trade.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

// 24 hour HH:mm:ss 12 houre hh:mm:ss
<wpfTool:DateTimeUpDown x:Name="tp_start" Height="25" Value="{Binding StartTime}" Format="Custom" FormatString="HH:mm:ss" ValueChanged="tp_start_ValueChanged" ToolTip="开始和停止时间一致表示没有停止时间"/>


// 获取
var dt = dtp_trade.Text;

private void tp_start_ValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
// 避免有输入单个数字的情况,例如: 9:00:00
var vlist = tp_start.Text.Split(":");
for (int i = 0; i < vlist.Length; i++)
{
if (vlist[i].Length <2 )
{
vlist[i] = $"0{vlist[i]}";
}
}
App.db.m_config[0].StartTime = $"{vlist[0]}:{vlist[1]}:{vlist[2]}";
App.db.Update_model<Model_config>(App.db.m_config[0]);
}

获取日期

datePickerCtl.SelectedDate = DateTime.Now;

var strDate = datePickerCtl.SelectedDate.Value.ToString("yyyy-MM-dd");

禁止选择日期

// 设置不能选择的日期
dp_start.BlackoutDates.Add(new CalendarDateRange(new DateTime(2021, 3, 1), new DateTime(2021, 3, 3)));

添加引用

添加 System.Windows.Forms 和 WindowsFormsIntegration 两个引用
在 Assemblies 里面搜索添加

// xaml 顶部添加
xmlns:wfi ="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
xmlns:wf ="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"

// 添加控件
<wfi:WindowsFormsHost Width="100">
<wf:DateTimePicker x:Name="tpStartDate" Format="Custom" CustomFormat="yyyy/MM/dd"/>
</wfi:WindowsFormsHost>
<wfi:WindowsFormsHost Width="80">
<wf:DateTimePicker x:Name="tpStartTime" Format="Time" ShowUpDown="True" />
</wfi:WindowsFormsHost>

// 大写的 HH 是24小时表示
<wfi:WindowsFormsHost Width="200">
<wf:DateTimePicker x:Name="tpStartDat" Format="Custom" CustomFormat="yyyy/MM/dd HH:mm:ss"/>
</wfi:WindowsFormsHost>

/*
Format:设置为Custom显示为年月日;设置为Time显示为时分秒
CustomFormat:设置显示样式
ShowUpDown:设置为true表示可以使用上下选择时间
获取控件中的时间DateTime dt = tpStartDate.Value;
获取当前时间日期减一天并赋值给时间控件:tpStartDate.Value = DateTime.Now.AddDays(-1);
*/

dpStartTime.Value = DateTime.ParseExact("07:29:59", "HH:mm:ss", null);
dpStopTime.Value = DateTime.ParseExact("19:29:59", "HH:mm:ss", null);