首页 新闻 会员 周边

怎么样WPF DataGrid获取所有单元格?

0
悬赏园豆:5 [已解决问题] 解决于 2014-08-26 21:48

界面初次加载,在给DataGrid1赋值后,立即获取所有行的时候就失败了

  tempIndex=0;

foreach (DataRowView item in DataGrid1.Items)
      { 

        此时的item有值

DataGridRow row = DataGrid1.ItemContainerGenerator.ContainerFromIndex(tempIndex) as DataGridRow;//此时row为空了 ContainerFromItem(item)也没用,

 tempIndex++;

我调式了半天 实在没招了 求指点啊

   }

 

 怎么样拿到DataGridRow?

 其实我就想给DataGrid1每个单元格做个ToolTip,为什么就这么难?

隔壁老王来了的主页 隔壁老王来了 | 初学一级 | 园豆:99
提问于:2014-08-25 19:15
< >
分享
最佳答案
0

row为空的原因是因为对象的类型不是目标类型,所以as转换结果为空(如果用强类型转换,应该抛出异常)。

跟踪下DataGrid的各种属性、item的各种属性看,我现在不方便写代码。

收获园豆:5
519740105 | 大侠五级 |园豆:5810 | 2014-08-25 21:20

应该在Loaded事件中处理

jello chen | 园豆:7306 (大侠五级) | 2014-08-26 11:06
void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            int index = 0;
            foreach (var item in this.dataGrid1.Items)
            {
                var row = dataGrid1.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
                if (row != null)
                {
                    row.ToolTip = "row" + (++index);
                }
            }
        }
jello chen | 园豆:7306 (大侠五级) | 2014-08-26 11:08

@jello chen: datagrid还有header和footer,此外的都能通过了?header和footer是肯定不能通过的。

519740105 | 园豆:5810 (大侠五级) | 2014-08-26 11:09

如果是想每个Cell添加ToolTip可以这么做:

<DataGrid AutoGenerateColumns="False" HorizontalAlignment="Left" Name="dataGrid1" VerticalAlignment="Top" ItemsSource="{Binding}" CanUserAddRows="False" CanUserDeleteRows="False" ToolTipService.ToolTip="datagrid">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}">
                    <DataGridTextColumn.CellStyle>
                        <Style TargetType="{x:Type DataGridCell}">
                            <Setter Property="ToolTip" Value="{Binding Name}" />
                        </Style>
                    </DataGridTextColumn.CellStyle>
                </DataGridTextColumn>
                <DataGridTextColumn Header="Age" Binding="{Binding Age}">
                    <DataGridTextColumn.CellStyle>
                        <Style TargetType="{x:Type DataGridCell}">
                            <Setter Property="ToolTip" Value="{Binding Age}" />
                        </Style>
                    </DataGridTextColumn.CellStyle>
                </DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
View Code

 

jello chen | 园豆:7306 (大侠五级) | 2014-08-26 11:30

@jello chen: 既然你能获得row了,那控制cell就更简单吧?row应该有cell集合属性的,好像也是items(或者columns试试)

519740105 | 园豆:5810 (大侠五级) | 2014-08-26 11:35

@519740105: 他主要是想Cell添加Tooltip,觉得在XAML设置CellStyle比较好些,回复错了,/尴尬

jello chen | 园豆:7306 (大侠五级) | 2014-08-26 11:51

@jello chen: 你上面贴出的代码不是有这个设置了吗?

519740105 | 园豆:5810 (大侠五级) | 2014-08-26 13:44
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册