我正在DataGrid控件中创建绑定DatePicker控件列。对于每个DatePicker控件,我想附加一个SelectedDateChangedEvent处理程序,但我很难做到这一点。
考虑以下WPF代码:
private void dg_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == "Event Date")
{
var f = new FrameworkElementFactory(typeof(DatePicker));
...
// I tried this:
//f.AddHandler(DatePicker.SelectedDateChangedEvent, new RoutedEventHandler(aRoutedEventHandler));
// and I tried this:
//f.AddHandler(DatePicker.SelectedDateChangedEvent, new SelectionChangedEventHandler(aSelectionChangedEventHandler));
e.Column = new DataGridTemplateColumn()
{
Header = e.Column.Header,
CellTemplate = new DataTemplate() { VisualTree = f },
};
}
}
private void aRoutedEventHandler(object sender, RoutedEventArgs e) { ... }
private void aSelectionChangedEventHandler(object sender, SelectionChangedEventArgs e) {...}
尝试任何一个事件处理程序都会导致"参数异常":
类型为'System '的第一次异常。在PresentationFramework.dll中发生了ArgumentException附加信息:处理程序类型无效。
正确的处理程序是什么?
您需要为DatePicker SelectedDateChangedEvent添加如下处理程序
f.AddHandler(DatePicker.SelectedDateChangedEvent, new EventHandler<SelectionChangedEventArgs>(aSelectionChangedEventHandler));
处理程序类型可以通过查看声明的公共事件中的DatePicker类来找到
public event RoutedEventHandler CalendarOpened;
public event RoutedEventHandler CalendarOpened;
public event EventHandler<DatePickerDateValidationErrorEventArgs>
public event EventHandler<SelectionChangedEventArgs> SelectedDateChanged;