C# 基础(二十四)将对象object转成时间类型DateTime。或转成一个时间控件DatePicker类型,然后拿出DatePicker.DateTime、DatePicker.Text

本文介绍了一个使用WPF和XAML进行界面设计与交互处理的示例,展示了如何通过XAML标记和C#代码实现用户界面元素的状态绑定与事件触发。包括日期选择器与按钮操作的详细说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、简介

开销小(较少的装箱解箱): 

 DateTime? dtEnd = null;
//dtEnd = obj as DateTime;//不能用
//var dtEnd = obj;//可以考虑
dtEnd = (DateTime)obj;//强制转换

但是我我们有时候想要,一次性可以传更多的东西(开销大):

 

dtEnd = (DateTime)obj;
DatePicker aa = obj as DatePicker;
string bb = aa.Text;
DateTime dd = (DateTime)aa.SelectedDate;

二、附件

 .xmal程序:

<UserControl x:Class="KeenRay.Modules.History.Views.ExInPortDlg"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:cc="clr-namespace:KeenRay.Controls;assembly=KeenRay.Controls"      
             xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
             xmlns:local="clr-namespace:KeenRay.Modules.History.Views"
             xmlns:prism="http://prismlibrary.com/"
             prism:ViewModelLocator.AutoWireViewModel="True"
             mc:Ignorable="d" 
             d:DesignHeight="270" d:DesignWidth="483">
    <Grid Name="rootGrid" Background="#dbdce1">
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="50"/>
            <RowDefinition Name="hidedRow1" Height="0"/>
            <RowDefinition />
        </Grid.RowDefinitions>
        <Canvas Grid.Row="0">
            <Label Canvas.Left="40" Content="选项:"></Label>
        </Canvas>

        <Canvas Grid.Row="1">
            <RadioButton  Name="radioImport" Content="导入" Canvas.Left="109" Canvas.Top="18" IsChecked="{Binding RadioImportIsChecked,Mode=TwoWay}">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="Checked">
                        <i:InvokeCommandAction Command="{Binding radioImportCheckedCommand}" CommandParameter="{Binding ElementName = radioImport}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </RadioButton>
            <RadioButton  Name="radioExport" Content="导出" Canvas.Left="300" Canvas.Top="18" IsChecked="{Binding RadioExportIsChecked,Mode=TwoWay}">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="Checked">
                        <i:InvokeCommandAction Command="{Binding radioExportCheckedCommand}" CommandParameter="{Binding ElementName = radioExport}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </RadioButton>
        </Canvas>

        <Grid Grid.Row="2">
            <Grid.RowDefinitions>
                <RowDefinition Height="30"/>
                <RowDefinition Height="40"/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <Canvas Grid.Row="0">
                <Label Content="导出选项:" Canvas.Left="40" Canvas.Top="6"/>
            </Canvas>
            <Canvas Grid.Row="1">
                <RadioButton  Name="radioExportCurSelect" Canvas.Left="109" Canvas.Top="15" Content="导出当前选择检查" IsChecked="{Binding radioExportCurSelectIsChecked,Mode=TwoWay}">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="Checked">
                            <i:InvokeCommandAction Command="{Binding radioExportCurSelectCheckedCommand}" CommandParameter="{Binding ElementName = radioExportCurSelect}"/>
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </RadioButton>
                <RadioButton Name="radioExportDateRange" Canvas.Left="300" Canvas.Top="15" Content="导出时间段检查" IsChecked="{Binding radioExportDateRangeIsChecked,Mode=TwoWay}">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="Checked">
                            <i:InvokeCommandAction Command="{Binding radioExportDateRangeCheckedCommand}" CommandParameter="{Binding ElementName = radioExportDateRange}"/>
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </RadioButton>
            </Canvas>
            <Canvas Grid.Row="2">
                <DatePicker Name="dpkDateStart" Style="{StaticResource ExPortDatePickerStyle}" Canvas.Left="109" Width="150">
                    <i:Interaction.Triggers>
                        <!--默认加载-->
                            <i:EventTrigger EventName="Loaded">
                            <i:InvokeCommandAction Command="{Binding dpkDateStartLoadedCommand}" CommandParameter="{Binding ElementName = dpkDateStart}"/>
                        </i:EventTrigger>
                        <!--选中日期-->
                        <i:EventTrigger EventName="SelectedDateChanged">
                            <i:InvokeCommandAction Command="{Binding dpkDateStartSelectedDateChangedCommand}" CommandParameter="{Binding ElementName = dpkDateStart}"/>
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </DatePicker>

                <DatePicker Name="dpkDateEnd"   Style="{StaticResource ExPortDatePickerStyle}" Canvas.Left="300" Width="150" SelectedDate="" Text="" Tag="">
                    <i:Interaction.Triggers>
                        <!--默认加载-->
                        <i:EventTrigger EventName="Loaded">
                            <i:InvokeCommandAction Command="{Binding dpkDateEndLoadedCommand}" CommandParameter="{Binding ElementName = dpkDateEnd}"/>
                        </i:EventTrigger>
                        
                        <!--选中日期-->
                        <i:EventTrigger EventName="SelectedDateChanged">
                            <i:InvokeCommandAction Command="{Binding dpkDateEndSelectedDateChangedCommand}" CommandParameter="dpkDateEnd"/>
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </DatePicker>
            </Canvas>
        </Grid>
        <Canvas Grid.Row="3">
            <cc:ImageButton  Content="{DynamicResource History.PrintSetting.Operate.Content}" Width="100" Height="30" Canvas.Right="200" Canvas.Left="246" Canvas.Top="5" FontSize="18" IsDefault="True" Foreground="#606467" DefaultImage="{StaticResource Public.EmptyButton122x52.Enable.Icon}"  PressedImage="{StaticResource Public.EmptyButton112x52.Touches.Icon}" Command="{Binding OperateCommand}"></cc:ImageButton>
            <cc:ImageButton  Content="{DynamicResource History.PrintSetting.Cancel.Content}" Width="100" Height="30" Canvas.Right="5" Canvas.Left="351" Canvas.Top="5" FontSize="18" Foreground="#606467" DefaultImage="{StaticResource Public.EmptyButton122x52.Enable.Icon}"  PressedImage="{StaticResource Public.EmptyButton112x52.Touches.Icon}" Command="{Binding CancelCommand}"></cc:ImageButton>
        </Canvas>
    </Grid>
</UserControl>

.cs程序

     private void DpkDateEnd_SelectedDateChanged(object obj)
        {
            //dtEnd = this.dpkDateEnd.SelectedDate;
            //var dtEnd = obj;
            dtEnd = (DateTime)obj;
            DatePicker aa = obj as DatePicker;
            string bb = aa.Text;
            DateTime dd = (DateTime)aa.SelectedDate;
            等等
        }

 

<think>我们正在处理关于C#DatePicker控件的使用教程和示例的请求。根据提供的引用,特别是引用[1]和[4],我们知道在WPF中DatePicker控件用于选择日期,并且属于WPF的日期控件类别。用户要求的是使用教程和示例,因此我们需要提供:1.基本使用:如何在XAML中添加DatePicker控件。2.常用属性:如何设置日期范围、日期格式等。3.事件处理:如何处理日期选择事件。4.代码示例:在C#代码中如何获取和设置DatePicker的值。根据引用[1],有一个简单的XAML示例。引用[2]提到了Calendar控件的多选范围设置,但DatePicker通常只选择单个日期。不过,DatePicker内部包含一个Calendar,因此可能支持类似属性。引用[4]将DatePicker和Calendar都归类为日期控件。注意:引用[3]是关于jQuery的,与C#无关,因此忽略。因此,我们将重点放在WPF的DatePicker控件上。步骤:1.添加DatePicker控件到XAML。2.设置属性(如日期范围、格式等)。3.处理SelectedDateChanged事件。4.在代码中操作DatePicker。由于引用[2]中提到了设置日期范围,我们可以通过设置DisplayDateStart和DisplayDateEnd属性来限制可选日期范围。示例代码结构:-XAML部分:展示如何添加DatePicker并设置属性。-C#部分:展示如何获取选中的日期以及处理事件。同时,我们还需要注意,DatePicker的SelectedDate属性是Nullable<DateTime>类型,因为可能没有选择日期。根据上述分析,我们组织回答如下:</think>### C# WPF DatePicker 控件使用教程 DatePicker 是 WPF 中用于日期选择的专用控件,属于 WPF 日期控件类别[^4]。它提供日历下拉界面,简化了日期输入操作。以下是核心用法和示例: --- #### **1. 基础使用** 在 XAML 中添加 DatePicker 控件: ```xml <Window x:Class="DatePickerExample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="DatePicker 示例" Height="350" Width="525"> <StackPanel Margin="15"> <DatePicker x:Name="myDatePicker"/> <TextBlock Margin="0,10" Text="{Binding SelectedDate, ElementName=myDatePicker}"/> </StackPanel> </Window> ``` - 效果:用户选择日期后,TextBlock 自动显示所选日期 - 关键属性:`SelectedDate`(存储当前选中的日期) --- #### **2. 常用属性设置** | **属性** | **说明** | **示例** | |--------------------|-----------------------------------|---------------------------------------------| | `DisplayDateStart` | 限制可选最小日期 | `<DatePicker DisplayDateStart="2023-01-01"/>` | | `DisplayDateEnd` | 限制可选最大日期 | `<DatePicker DisplayDateEnd="2025-12-31"/>` | | `SelectedDateFormat` | 日期显示格式(Short/Long) | `<DatePicker SelectedDateFormat="Long"/>` | | `IsDropDownOpen` | 强制展开日历下拉框 | `<DatePicker IsDropDownOpen="True"/>` | --- #### **3. 事件处理** 处理日期选择变化事件: ```csharp // XAML 中添加事件绑定 <DatePicker SelectedDateChanged="DatePicker_SelectedDateChanged"/> // C# 代码 private void DatePicker_SelectedDateChanged(object sender, SelectionChangedEventArgs e) { if (myDatePicker.SelectedDate.HasValue) { DateTime selected = myDatePicker.SelectedDate.Value; MessageBox.Show($"选择的日期: {selected.ToString("yyyy-MM-dd")}"); } } ``` --- #### **4. 代码后台操作** ```csharp // 设置默认日期 myDatePicker.SelectedDate = DateTime.Now.AddDays(7); // 获取日期值 if (myDatePicker.SelectedDate != null) { DateTime userSelectedDate = myDatePicker.SelectedDate.Value; } // 清空选择 myDatePicker.SelectedDate = null; ``` --- #### **5. 进阶功能示例** **日期范围验证**(禁止选择周末): ```csharp myDatePicker.BlackoutDates.AddDatesInPast(); // 禁用过去日期 myDatePicker.BlackoutDates.Add( new CalendarDateRange(DateTime.Today.AddDays(1), DateTime.Today.AddDays(5))); // 禁用特定范围 // 自定义日期验证 myDatePicker.DateValidationError += (s, e) => { if (e.Exception != null) { MessageBox.Show("无效日期: " + e.Text); e.ThrowException = false; } }; ``` > **注意**:DatePicker 内部集成 Calendar 控件,可通过`CalendarStyle`属性完全自定义日历界面[^2]。 --- ### 常见问题解决方案 1. **日期绑定失败** 确保使用 `SelectedDate` 而非 `Text` 属性,并检查绑定模式: ```xml <TextBlock Text="{Binding SelectedDate, ElementName=myDatePicker, StringFormat='yyyy年MM月dd日'}"/> ``` 2. **空值处理** 始终检查 `SelectedDate.HasValue`,因为未选择时值为 `null`。 3. **跨文化适配** 设置 `Language` 属性自动适配本地日历格式: ```xml <DatePicker Language="zh-CN"/> ``` [^1]: 基础控件嵌入方法 [^2]: 日期范围控制技术 [^4]: WPF 控件分类标准
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我爱AI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值