English 中文(简体)
获取WPF中数据Grid的细胞价值?
原标题:Access to cell values of a DataGrid in WPF?

We have such a scenario that we have a page including a DataGrid, and now we want to get all data from this DataGrid, but without accessing to the underlying item source of it, i.e., we want to access to the data directly from the DataGrid. It seems to be tricky but not impossible. I found many articles, like this: DataGridHelper, and this: Get WPF DataGrid row and cell, and many other ones. They are basically the same thing: to define the extension methods on DataGrid with help of another GetVisualChild function to find the target DataGridCell object. However, when I am using it, I can t find the target cell. Specifically, Each row in the DataGrid corresponds to one item from a collection of the DataContext, let s say, it is a collection of type "Employee", and each column of the DataGrid corresponds one property of class Employee, e.g, the Name, Gender, Age. Now my problem is, the above-mentioned GetCell() function always finds a DataGridCell with one Employee object as its content (the property of Content in DataGridCell), and can t go further into each property, no matter what column index I give it. For example, in the GetCell function, there is one line: Dim cell As DataGridCell = DirectCast(presenter.ItemContainerGenerator.ContainerFromIndex(column), DataGridCell), where the presenter is a DataGridCellsPresenter I got which representing the row I choose, and as soon as I give the column index, naturally I am expecting it to return the control for selected property at position I specified. But it just doesn t work as expected. Any help would be appreciated!

最佳回答

页: 1 仅凭数据网中显示的非虚拟项目,即浏览量(加上以上和低于滚动观察限额的几行数)的计算结果,你就受到限制。

若要获得所有囚室的数值,你必须执行对每个牢房具有约束力的一栏。

  1. 查阅<代码>DataGrid.Items的收集。 由此可见,任何以过滤标准或习俗 p等掩盖的物品都将排除在外。 如果你打算这样做的话,请填写。 DataGrid.ItemsSource.Cast<object>ToList( calls。

  2. 现在查阅数据网的所有栏目,即DataGrid.Columns。 假设它们属于任何类别,但<代码>DataGridTemplateColum,下面第3步将提取电池级值。 对于模板栏,你必须具体说明代表单元整个模板的一些财产价值。 页: 1 a 优秀候选人。

  3. Extract the DataGridTextColumn.Binding, DataGridCheckBoxColumn.Binding, DataGridComboBoxColumn.SelectedValueBinding or DataGridComboBoxColumn.SelectedItemBinding. Then for each item from step 1, execute the binding to extract the value.

<><><>>>>

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        string gridContent = string.Empty;

        foreach(var item in MyDataGrid.Items)
        {
            foreach (var column in MyDataGrid.Columns)
            {
                var textCol = column as DataGridTextColumn;
                var checkCol = column as DataGridCheckBoxColumn;
                var comboCol = column as DataGridComboBoxColumn;
                var templateCol = column as DataGridTemplateColumn;

                if (textCol != null)
                {
                    var propertyName = ((Binding)textCol.Binding).Path.Path;
                    var value
                            = item.GetType().GetProperty(
                                  propertyName).GetValue(
                                  item,
                                  new object[] {});

                    if (((Binding)textCol.Binding).Converter != null)
                    {
                        value
                            = ((Binding)checkCol.Binding).Converter.Convert(
                                value,
                                typeof(object),
                                ((Binding)checkCol.Binding).ConverterParameter,
                                ((Binding)checkCol.Binding).ConverterCulture);
                    }
                    gridContent = gridContent + "	" + value.ToString();
                }
                if (checkCol != null)
                {
                    var propertyName = ((Binding)checkCol.Binding).Path.Path;
                    object value
                        = item.GetType().GetProperty(
                               propertyName).GetValue(
                               item,
                               new object[] { });

                    if (((Binding)checkCol.Binding).Converter != null)
                    {
                        value
                            = ((Binding)checkCol.Binding).Converter.Convert(
                                value,
                                typeof(object),
                                ((Binding)checkCol.Binding).ConverterParameter,
                                ((Binding)checkCol.Binding).ConverterCulture);
                    }
                    gridContent = gridContent + "	" + value.ToString();
                }
                if (comboCol != null)
                {
                    var propertyName = string.Empty;
                    if (comboCol.SelectedValueBinding != null)
                    {
                        propertyName
                          = ((Binding)comboCol.SelectedValueBinding).Path.Path;
                    }
                    else if (!string.IsNullOrEmpty(comboCol.SelectedValuePath))
                    {
                        propertyName = comboCol.SelectedValuePath;
                    }
                    else if (!string.IsNullOrEmpty(comboCol.DisplayMemberPath))
                    {
                        propertyName = comboCol.DisplayMemberPath;
                    }

                    var value = item.GetType().GetProperty(
                         propertyName).GetValue(
                            item,
                            new object[] { });

                    if (comboCol.SelectedValueBinding != null
                        && ((Binding)comboCol.SelectedValueBinding).Converter != null)
                    {
                        var bnd = (Binding)comboCol.SelectedValueBinding; 
                        value
                            = bnd.Converter.Convert(
                                value,
                                typeof(object),
                                bnd.ConverterParameter,
                                bnd.ConverterCulture);
                    }
                    gridContent = gridContent + "	" + value.ToString();
                }
                if (templateCol != null)
                {
                    var propertyName = templateCol.SortMemberPath;
                    var value
                        = item.GetType().GetProperty(
                             propertyName).GetValue(
                               item,
                               new object[] { });

                    gridContent = gridContent + "	" + value.ToString();
                }
            }

            gridContent = gridContent + "
";
        }

        MessageBox.Show(gridContent);
    }
}
问题回答

我认识到这是一个老问题,但我寻求简单的解决办法,最后找到解决办法。 其他人可能喜欢简单。 以下例子按特定栏搜索数据网,以了解预期价值,如果发现数据集将选择该行。

    private void dgSetRow(DataGrid dg, string sColHeader, int iFindValue)
    {

        foreach (DataRowView drv in dg.Items )
        {
            // compare value in datarow of view
            if (iFindValue == (int)drv.Row[sColHeader])
            {
                // select item
                dg.SelectedItem = drv;
                dg.ScrollIntoView(drv);
            }
        }
    }




相关问题
WPF convert 2d mouse click into 3d space

I have several geometry meshes in my Viewport3D, these have bounds of (w:1800, h:500, d:25). When a user clicks in the middle of the mesh, I want the Point3D of (900, 500, 25)... How can I achieve ...

Editing a xaml icons or images

Is it possible to edit a xaml icons or images in the expression design or using other tools? Is it possible to import a xaml images (that e.g you have exported) in the expression designer for editing?...

WPF: writing smoke tests using ViewModels

I am considering to write smoke tests for our WPF application. The question that I am faced is: should we use UI automation( or some other technology that creates a UI script), or is it good enough to ...

WPF - MVVM - NHibernate Validation

Im facing a bit of an issue when trying to validate a decimal property on domain object which is bound to a textbox on the view through the viewmodel. I am using NHibernate to decorate my property on ...

How do WPF Markup Extensions raise compile errors?

Certain markup extensions raise compile errors. For example StaticExtension (x:Static) raises a compile error if the referenced class cannot be found. Anyone know the mechanism for this? Is it baked ...

WPF design-time context menu

I am trying to create a custom wpf control, I m wondering how I can add some design-time features. I ve googled and can t seem to get to my goal. So here s my simple question, how can I add an entry ...

How to combine DataTrigger and EventTrigger?

NOTE I have asked the related question (with an accepted answer): How to combine DataTrigger and Trigger? I think I need to combine an EventTrigger and a DataTrigger to achieve what I m after: when ...

热门标签