使用CellEditEnding事件验证WPF DataGrid中的DatePicker值

时间:2012-11-27 18:20:59

标签: wpf datagrid

我正在使用WPF DataGrid的CellEditEnding事件来验证数据并执行其他计算。我有TextBoxes和DatePickers作为DataGridTemplateColumns。

以下是我调用事件处理程序的方法

    private void OnCellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    {
        if (e.EditAction == DataGridEditAction.Cancel) return;

        DataGridCellEditEndingCommandParameter p = new DataGridCellEditEndingCommandParameter();
        if (e.Column != null)
        {
            p.BindingPropertyName = e.Column.SortMemberPath;
            if (e.Column.Header != null)
                p.ColumnHeaderName = e.Column.Header.ToString();
        }

        TextBox t = e.EditingElement as TextBox;
        if (t != null) 
            p.EndingElementValue = t.Text;
        //else if (e.EditingElement as DatePicker) 

        if (e.Row != null) p.RowItem = e.Row.Item;

        p.EventArgs = e;
        p.Sender = sender as DataGrid;

        CommandParameter = p;
        ExecuteCommand();
    }

我将EditingElement转换为TextBox以读取用户输入的值,对DatePicker执行相同操作,但在编辑DatePicker时结果为null。

<DataGridTemplateColumn x:Name="fxFwd"  Header="Value Date" Width="70" SortMemberPath = "fwFwdDate" CanUsersort = "True">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path= fxFwdDate, 
            ConverterCulture={x:Static gl:CultureInfo.CurrentCulture}, 
            StringFormat=\{0:d\}}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <DatePicker SelectedDate="{Binding Path=fxFwdDate,
                ConverterCulture={x:Static gl:CultureInfo.CurrentCulture}, Mode=TwoWay,
                ValidatesOnExceptions=true, NotifyOnValidationError=true}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

当我在更改DatePicker的值后检查EditingElement时,它将作为ContentPresenter而不是DatePicker接收。

提前致谢

1 个答案:

答案 0 :(得分:3)

x:Name控件上设置DatePicker -

<DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate>
        <DatePicker x:Name="datePicker" />
    </DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>

你可以像这样 -

在代码隐藏中获取DatePicker控件
ContentPresenter contentPresenter = e.EditingElement as ContentPresenter;
DataTemplate editingTemplate = contentPresenter.ContentTemplate;
DatePicker dp = editingTemplate.FindName("datePicker", contentPresenter)
                            as DatePicker ;