visual valor obtener mostrar hora guardar fecha custom control actual c# xaml datepicker windows-store-apps timepicker

mostrar - obtener el valor de un datetimepicker c#



Combinando los valores de Datepicker y Timepicker Win 8.1 (6)

Intento usar un Datepicker + un Timepicker juntos para devolver un DateTime que se puede almacenar en una base de datos. Por ejemplo, me gustaría tener un StartDate y un EndDate (si corresponde) para una reunión programada.

¿Cómo podría combinar los valores en el formato correcto que manejaría una base de datos SQL?

Cualquier comentario sería genial.


Estaba buscando una respuesta más exhaustiva a esta pregunta, así que esto es lo que he reunido y que funciona bastante bien para mí.

Primero creamos un control de usuario que envuelve los controles datepicker y timepicker. En el constructor puede especificar el tipo de control que le gustaría visualizar (DATE, TIME, o DATE_TIME). Ambos recolectores estarán vinculados a la misma propiedad de fecha dentro del control. Cuando se usa, el valor de fecha del control de usuario se puede establecer y obtener usando la propiedad "TheDate" del control.

DateTimeControl dtc = new DateTimeControl("DATE_TIME"); dtc.TheDate = DateTime.Now;

<UserControl x:Class="IFS.FSMW.Architecture.Controls.DateTimeControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:IFS.FSMW.Architecture.Controls" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <DatePicker Margin="0,0,10,0" x:Name="theDatePicker"/> <TimePicker Grid.Column="1" x:Name="theTimePicker"/> </Grid>

public sealed partial class DateTimeControl : UserControl { public String ControlType { get { return (String)GetValue(ControlTypeProperty); } set { SetValue(ControlTypeProperty, value); } } // Using a DependencyProperty as the backing store for ControlType. This enables animation, styling, binding, etc... public static readonly DependencyProperty ControlTypeProperty = DependencyProperty.Register("ControlType", typeof(String), typeof(DateTimeControl), new PropertyMetadata("")); public DateTime TheDate { get { return (DateTime)GetValue(TheDateProperty); } set { SetValue(TheDateProperty, value); } } // Using a DependencyProperty as the backing store for TheDate. This enables animation, styling, binding, etc... public static readonly DependencyProperty TheDateProperty = DependencyProperty.Register("TheDate", typeof(DateTime), typeof(DateTimeControl), new PropertyMetadata(DateTime.Now)); public DateTimeControl() { this.InitializeComponent(); } public DateTimeControl(String ControlTypeIn) { this.InitializeComponent(); ControlType = ControlTypeIn; switch (ControlType.ToUpper()) { case "DATE_TIME": this.theDatePicker.Visibility = Windows.UI.Xaml.Visibility.Visible; this.theTimePicker.Visibility = Windows.UI.Xaml.Visibility.Visible; break; case "DATE": this.theDatePicker.Visibility = Windows.UI.Xaml.Visibility.Visible; this.theTimePicker.Visibility = Windows.UI.Xaml.Visibility.Collapsed; break; case "TIME": this.theDatePicker.Visibility = Windows.UI.Xaml.Visibility.Collapsed; this.theTimePicker.Visibility = Windows.UI.Xaml.Visibility.Visible; break; default: break; } DateTimeToDateTimeOffsetConverter converter = new DateTimeToDateTimeOffsetConverter(); Binding bdDate = new Binding(); bdDate.Mode = BindingMode.TwoWay; bdDate.Converter = converter; bdDate.Path = new PropertyPath("TheDate"); bdDate.Source = this; Binding bdTime = new Binding(); bdTime.Mode = BindingMode.TwoWay; bdTime.Converter = converter; bdTime.ConverterParameter = TheDate; bdTime.Path = new PropertyPath("TheDate"); bdTime.Source = this; if (ControlType.ToUpper() == "DATE_TIME") { theDatePicker.SetBinding(DatePicker.DateProperty, bdDate); theTimePicker.SetBinding(TimePicker.TimeProperty, bdTime); } else if (ControlType.ToUpper() == "DATE") { theDatePicker.SetBinding(DatePicker.DateProperty, bdDate); } else if (ControlType.ToUpper() == "TIME") { theTimePicker.SetBinding(TimePicker.TimeProperty, bdTime); } } } public class DateTimeToDateTimeOffsetConverter :IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { try { if (targetType == typeof(TimeSpan)) { if (parameter != null) { DateTime dt = (DateTime)value; //Get the timespan from subtracting the date from the original DateTime //this returns a timespan representing the time component of the DateTime TimeSpan ts = dt - dt.Date; return ts; } else { return new DateTimeOffset(DateTime.Now); } } DateTime date = (DateTime)value; return new DateTimeOffset(date); } catch (Exception ex) { return DateTimeOffset.MinValue; } } public object ConvertBack(object value, Type targetType, object parameter, string language) { try { if (value.GetType() == typeof(TimeSpan)) { TimeSpan ts = (TimeSpan)value; DateTime dateParam = (DateTime)parameter; return new DateTime(dateParam.Year,dateParam.Month,dateParam.Day,ts.Hours,ts.Minutes,ts.Seconds); } DateTimeOffset dto = (DateTimeOffset)value; return dto.DateTime; } catch (Exception ex) { return DateTime.MinValue; } } }


La respuesta de @ user3216360 me puso en el camino correcto para resolver esto para mi propia aplicación. Desafortunadamente, las consolidaciones que sugirió se mantuvieron dando como resultado que el selector de Fecha se restablezca al valor inicial cada vez que se cambia el valor del selector de Tiempo. Tomé un enfoque ligeramente diferente y conecté dos propiedades de dependencia adicionales para resolver el problema. Esas dos propiedades de dependencia pueden actualizar la propiedad SelectedDateTime. Hasta ahora, parece estar funcionando bien!

using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Data; namespace MyApp.Views { public sealed partial class DateTimePickerControl : UserControl { public static readonly DependencyProperty SelectedDateTimeProperty = DependencyProperty.Register("SelectedDateTime", typeof (DateTime), typeof (DateTimePickerControl), new PropertyMetadata(DateTime.Now)); public static readonly DependencyProperty SelectedDateProperty = DependencyProperty.Register("SelectedDate", typeof (DateTimeOffset), typeof (DateTimePickerControl), new PropertyMetadata(DateTimeOffset.Now, OnDateChanged)); public static readonly DependencyProperty SelectedTimeProperty = DependencyProperty.Register("SelectedTime", typeof (TimeSpan), typeof (DateTimePickerControl), new PropertyMetadata(TimeSpan.FromHours(12), OnTimeChanged)); public DateTimePickerControl() { InitializeComponent(); var bdDate = new Binding { Mode = BindingMode.TwoWay, Path = new PropertyPath("SelectedDate"), Source = this }; var bdTime = new Binding { Mode = BindingMode.TwoWay, Path = new PropertyPath("SelectedTime"), Source = this }; PART_DatePicker.SetBinding(DatePicker.DateProperty, bdDate); PART_TimePicker.SetBinding(TimePicker.TimeProperty, bdTime); } public DateTimeOffset SelectedDate { get { return (DateTimeOffset) GetValue(SelectedDateProperty); } set { SetValue(SelectedDateProperty, value); } } public DateTime SelectedDateTime { get { return (DateTime) GetValue(SelectedDateTimeProperty); } set { SetValue(SelectedDateTimeProperty, value); } } public TimeSpan SelectedTime { get { return (TimeSpan) GetValue(SelectedTimeProperty); } set { SetValue(SelectedTimeProperty, value); } } private static void OnDateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var instance = d as DateTimePickerControl; if (instance == null) { return; } var dto = (DateTimeOffset) e.NewValue; TimeSpan ts = instance.SelectedTime; instance.SelectedDateTime = new DateTime(dto.Year, dto.Month, dto.Day, ts.Hours, ts.Minutes, ts.Seconds); } private static void OnTimeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var instance = d as DateTimePickerControl; if (instance == null) { return; } DateTimeOffset dto = instance.SelectedDate; var ts = (TimeSpan) e.NewValue; instance.SelectedDateTime = new DateTime(dto.Year, dto.Month, dto.Day, ts.Hours, ts.Minutes, ts.Seconds); } } }


Puede lograr esto vinculando tanto el DatePicker como el TimePicker al mismo valor de DateTime. TimePicker se uniría a la propiedad DateTime.TimeOfDay

<DatePicker Header="Date" Date="{Binding Date}"/> <TimePicker Header="Time" Time="{Binding Date.TimeOfDay}"/>


Tengo esto para trabajar.

String dateTimeString = ""; DateTime dateTime = DateTime.MinValue; dateTimeString = DateTime.Parse(datePicker.Value.ToString()).ToString("MM/dd/yyyy") + " " + DateTime.Parse(timePicker.Value.ToString()).ToString("h:mm tt"); dateTime = DateTime.Parse(dateTimeString);

No sé por qué, pero arroja una excepción si intenta formatear desde Value Ie datePicker.Value.ToString("MM/dd/yyyy")


Tratar

DateTime myDate = DatePickerControl.Date.Date.Add(TimePickerControl.Time);


prueba esto,

DateTime myDate= ((DateTime)DatePicker.Value).Date.Add(((DateTime)TimePicker.Value).TimeOfDay);