Reputation: 5009
I am always confused with the type DateTime
. In our WPF program we have an DateTime
property exposed by the ViewModel and need to be bind to a Control/Controls in the View. But apparently since the DateTime
has both Date part and Time part and we'd like to show them both/let the user to modify both. So I think we need one DatePicker
for date part and one TextBox
for time part (with format string), but I can't think of the straightforward way to define such Control/Binding in XAML
Googling with "WPF DateTime Binding" doesn't give me many references (why do most of the examples show a binding to DatePicker, when it is obviously a valid requirement to show time as well).
Can somebody tell me how to do that?
Upvotes: 0
Views: 1103
Reputation: 3113
You could use the Extended WPF Toolkit DateTimePicker control;
You can get this via nuget for your solution. Then simply bind to the value property of the DateTimePicker.
XAML:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="145*"></RowDefinition>
<RowDefinition Height="31*"></RowDefinition>
<RowDefinition Height="144*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<xctk:DateTimePicker Grid.Row="1" Value="{Binding Path=MyDateTime}" Grid.Column="1"/>
</Grid>
VB:
Imports System.ComponentModel
Class MainWindow : Implements INotifyPropertyChanged
Private _myDateTime As DateTime = "#28/04/2014 07:11:00 AM#"
Public Property MyDateTime As DateTime
Get
Return _myDateTime
End Get
Set(value As DateTime)
If _myDateTime <> value Then
_myDateTime = value
OnPropertyChanged("MyDateTime")
End If
End Set
End Property
Protected Sub OnPropertyChanged(ByVal PropertyName As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(PropertyName))
End Sub
Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
Public Sub New()
InitializeComponent()
Me.DataContext = Me
End Sub
End Class
Upvotes: 1