1

我正在使用 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 被接收。

提前致谢

4

1 回答 1

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 ;
于 2012-11-27T18:26:53.340 回答