FrameworkElementFactory

时间:2015-07-29 13:58:42

标签: wpf visual-studio-2013 datagrid datepicker event-handling

我在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.ArgumentException'的第一次机会异常。发生在PresentationFramework.dll中   附加信息:处理程序类型无效。

使用的正确处理程序是什么?

1 个答案:

答案 0 :(得分:0)

您需要为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;