简体   繁体   English

如何访问WPF DataGrid中的控件

[英]How do I access the controls in a WPF DataGrid

In good old (well!!) WinForms days the datagrids row used to the be the actual control and you could then access the DataItem. 在WinForms的旧版本中(好!),datagrids行曾经是实际的控件,然后您可以访问DataItem。

In WPF its all flipped and dataGrid.Items is just the source data. 在WPF中,所有翻转的内容和dataGrid.Items只是源数据。

I am probably doing this the wrong way round as im a bit of a WPF newb but how can I iterate through the rows of my gridview grabbing the values from certain labels, textboxes etc? 我可能会像WPF newb那样以错误的方式进行处理,但是如何在gridview的行中进行迭代以获取某些标签,文本框等的值呢?

Yes, you are doing this the wrong way round. 是的,您这样做的方向是错误的。 What you should be doing is iterating through the items in your data source - it's where all the values are, after all. 您应该做的是遍历数据源中的项目-毕竟这是所有值所在的位置。

It's possible to iterate through the WPF objects, but it's not trivial. 可以遍历WPF对象,但这并不简单。 And there's a significant problem that you'll run into if you try. 如果尝试尝试,则会遇到一个重大问题。

You can use the VisualTreeHelper class to search the visual tree and find the DataGrid 's descendant objects. 您可以使用VisualTreeHelper类搜索可视树并找到DataGrid的后代对象。 If you play with this long enough, eventually you'll figure out how to find the specific controls you're looking for. 如果玩了这么长时间,最终您将弄清楚如何找到想要的特定控件。 But the DataGrid (actually, the VirtualizingStackPanel in its control template) virtualizes its visual children. 但是, DataGrid (实际上是其控制模板中的VirtualizingStackPanel )可以虚拟化其可视子级。 If an item hasn't appeared on the screen yet, its WPF objects haven't been created yet, and you won't find them in the visual tree. 如果项目尚未出现在屏幕上,则尚未创建其WPF对象,并且您不会在可视树中找到它们。 You may not be able to find what you're looking for, not because you don't have a way of finding it, but because it doesn't exist. 您可能无法找到所需的内容,不是因为您没有找到它的方法,而是因为它不存在。

If you're using value converters and formatting in your bindings (which is the only reason I can think of that you'd want to look at the WPF objects and not the underlying data items), I'm afraid the answer is: don't do that. 如果您在绑定中使用值转换器和格式设置(这是我能想到的,您想查看WPF对象而不是基础数据项的唯一原因),恐怕答案是:不要不要那样做。 Do the value conversion and formatting in your data source, and expose the results as properties that can be bound to directly. 在数据源中进行值转换和格式设置,并将结果显示为可以直接绑定的属性。

It's certainly possible to use WPF without using the MVVM pattern. 当然可以在不使用MVVM模式的情况下使用WPF。 But this is the kind of brick wall that you can run into if you don't. 但这是您可能碰到的那种砖墙。

You can use this 你可以用这个

    public DataGridRow TryFindRow(object item, DataGrid grid)
    {
        // Does not de-virtualize cells
        DataGridRow row = (DataGridRow)(grid as ItemsControl).ItemContainerGenerator.ContainerFromItem(item);

        return row;
    }

where item represent the data displayed on the row. 其中item代表该行上显示的数据。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM