我正在尝试为DateTimePicker
创建一个Loaded事件,它将从DateTime
正在使用的DateTimePicker
对象中获取值,然后转换{{1}并将其设置回来。
代码:
DateTime
XAML:
private void dateTimePicker_Loaded(object sender, RoutedEventArgs e) {
DateTimePicker dateTimePicker = (DateTimePicker)sender;
DateTime dateTime = (DateTime)dateTimePicker.DataContext;
}
我在代码的第二行遇到了崩溃。
未处理的异常:指定的强制转换无效。
<toolkit:DateTimePicker DataContext="MyDateTime" Value="{Binding Path=MyDateTime, Mode=TwoWay}" Loaded="dateTimePicker_Loaded" Format="SortableDateTime"/>
是:
答案 0 :(得分:1)
您尚未正确设置DataContext
。尝试
<toolkit:DateTimePicker DataContext="{Binding Path=MyDateTime}" Value="{Binding ,Mode=TwoWay}" Loaded="dateTimePicker_Loaded" Format="SortableDateTime"/>
答案 1 :(得分:1)
您尚未正确绑定DataContext
。使用此:
<toolkit:DateTimePicker DataContext={Binding MyDateTime}" Value="{Binding ., Mode=TwoWay}" Loaded="dateTimePicker_Loaded" Format="SortableDateTime"/>