2013-10-31 92 views
0

我正在嘗試爲DateTimePicker創建一個加載事件,它將從DateTime對象中獲取DateTimePicker用作上下文的值,然後轉換DateTime並將其設置回。從DateTimePicker獲取上下文

代碼:

private void dateTimePicker_Loaded(object sender, RoutedEventArgs e) { 
     DateTimePicker dateTimePicker = (DateTimePicker)sender; 
     DateTime dateTime = (DateTime)dateTimePicker.DataContext; 
    } 

XAML:

  <toolkit:DateTimePicker DataContext="MyDateTime" Value="{Binding Path=MyDateTime, Mode=TwoWay}" Loaded="dateTimePicker_Loaded" Format="SortableDateTime"/> 

我得到一個崩潰的代碼的第二行。 未處理的異常:指定的轉換無效。 DataContext是:

回答

1

您沒有正確綁定DataContext。使用這個:

<toolkit:DateTimePicker DataContext={Binding MyDateTime}" Value="{Binding ., Mode=TwoWay}" Loaded="dateTimePicker_Loaded" Format="SortableDateTime"/> 
+1

完美謝謝。 – ThingWings

+0

@yoyo很高興它解決了!祝你好運! – gleng

1

您尚未正確設置DataContext。請嘗試

<toolkit:DateTimePicker DataContext="{Binding Path=MyDateTime}" Value="{Binding ,Mode=TwoWay}" Loaded="dateTimePicker_Loaded" Format="SortableDateTime"/> 
+0

未處理的異常:雙向綁定需要Path或XPath。 InnerException:雙向綁定需要Path或XPath。 – ThingWings

+0

逗號在表達式中缺失 – Nitin