从DateTimePicker获取上下文

时间:2013-10-31 15:08:55

标签: c# wpf xaml datetimepicker

我正在尝试为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"/> 是:

2 个答案:

答案 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"/>