我有一个 WPF Datagrid,其中一列是日期列。
所以我使用了 DataTemplateColumn 如下
<my:DataGridTemplateColumn
CellTemplate="{StaticResource EffDateDateTimePickerControl}"
CellEditingTemplate="{StaticResource addrEffDate}"
Header="Effective Date"/>
在我的资源文件中,我编写了以下代码:
<Style TargetType="{x:Type my:Calendar}" x:Key="CalenderControlTemplate">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="my:Calendar" >
<my:CalendarItem Name="myCalendarItem"
Background="White"
BorderBrush="Black"
BorderThickness="1"
VerticalAlignment="Center" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<DataTemplate x:Key="EffDateDateTimePickerControl">
<Label x:Name="lblEffDate" Content="{Binding effectiveDate,Mode=TwoWay}" ></Label>
</DataTemplate>
<DataTemplate x:Key="addrEffDate">
<my:DatePicker x:Name="dpEffDate" Text="{Binding Path=effectiveDate,Mode=TwoWay}"
SelectedDate="{Binding Now}" DisplayDateStart="{Binding Now}"
CalendarStyle="{DynamicResource CalenderControlTemplate}" />
</DataTemplate>
问题是当我单击 DatePicker 控件时,默认日期设置为 1/1/0001?
如何将我的日期选择器设置为当前日期。
最佳答案
除非您在 DataContext
中拥有房产叫 Now
,您的 Bindings
会失败。相反,您应该使用 {x:Static}
语法如下:
<DataTemplate x:Key="addrEffDate">
<my:DatePicker x:Name="dpEffDate" Text="{Binding Path=effectiveDate,Mode=TwoWay}"
SelectedDate="{x:Static sys:DateTime.Now}" DisplayDateStart="{x:Static sys:DateTime.Now}"
CalendarStyle="{DynamicResource CalenderControlTemplate}" />
</DataTemplate>
自
DateTime
不在标准 XAML 命名空间中,您需要向根元素添加 xmlns 声明:<UserControl xmlns:sys="clr-namespace:System;assembly=mscorlib" ...
关于wpf - 将 WPF 日期选择器的默认日期设置为当前日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3662506/