【问题标题】:Validating DatePicker value in WPF DataGrid using CellEditEnding Event使用 CellEditEnding 事件验证 WPF DataGrid 中的 DatePicker 值
【发布时间】:2012-11-27 18:20:59
【问题描述】:

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

提前致谢

【问题讨论】:

    标签: wpf datagrid


    【解决方案1】:

    在您的 DatePicker 控件上设置 x:Name -

    <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 ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-19
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 2019-02-02
      • 2015-09-10
      • 1970-01-01
      相关资源
      最近更新 更多