前端代码:

<Window x:Class="DataGridPractice.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DataGridPractice"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid Margin="0,0,0,214" Loaded="Grid_Loaded"> <Grid.Resources>
<DataTemplate x:Key="DataGridTemplateA">
<DataGrid Name="DataGrid2"
HeadersVisibility="None"
CanUserAddRows="False" CanUserDeleteRows="False"
CanUserResizeColumns="False" CanUserResizeRows="False"
CanUserReorderColumns="False" CanUserSortColumns="False"
AutoGenerateColumns="False" HorizontalAlignment="Left"
>
<DataGrid.Columns>
<DataGridTextColumn DisplayIndex="0" Binding="{Binding name, Mode=TwoWay}"/>
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
</Grid.Resources> <DataGrid Name="DataGrid1"
CanUserAddRows="False" CanUserDeleteRows="False"
CanUserResizeColumns="False" CanUserResizeRows="False"
CanUserReorderColumns="False" CanUserSortColumns="False"
AutoGenerateColumns="False" HorizontalAlignment="Left"
VerticalContentAlignment="Center"> <DataGrid.Columns> <DataGridTextColumn DisplayIndex="0" Binding="{Binding id, Mode=TwoWay}" /> <DataGridTextColumn DisplayIndex="1" Binding="{Binding name, Mode=TwoWay}"/> <DataGridTextColumn DisplayIndex="2" Binding="{Binding age, Mode=TwoWay}"/> <DataGridTextColumn DisplayIndex="3" Binding="{Binding TotalCount, Mode=TwoWay}"/> <DataGridTemplateColumn DisplayIndex="4" CellTemplate="{StaticResource DataGridTemplateA}" IsReadOnly="True" Header="2"/> </DataGrid.Columns>
</DataGrid>
<TextBox HorizontalAlignment="Left" Height="38" Margin="117,310,0,-143" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="154" LostFocus="TextBox_LostFocus"/>
</Grid>
</Window>

后端代码:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading; namespace DataGridPractice
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LoadData();
}
public List<Person> list { get; set; } public List<Character> characterlist { get; set; }
public void LoadData()
{
Random r = new Random();
list = new List<Person>(); //Person person = new Person();
//person.id = 1;
//person.name = "张三1";
//person.age = r.Next(100);
//person.TotalCount = 5;
//list.Add(person); characterlist = new List<Character>(); Character chara1 = new Character();
chara1.name = "A";
characterlist.Add(chara1); Character chara2 = new Character();
chara2.name = "B";
characterlist.Add(chara2); Character chara3 = new Character();
chara3.name = "C";
characterlist.Add(chara3); for (int i = 0; i < 9; i++)
{ if (i > 1)
break; Person person = new Person();
person.id = i + 1;
person.name = "张三" + i;
person.age = r.Next(100);
person.TotalCount = 5; list.Add(person);
}
} private void Grid_Loaded(object sender, RoutedEventArgs e)
{
DataGrid1.ItemsSource = list; DataGridTemplateColumn templeColumn = DataGrid1.Columns[4] as DataGridTemplateColumn;
if (templeColumn == null) return; for (int i = 0; i < DataGrid1.Items.Count; i++)
{
DataGridCell dataGridCell = GetDataGridCell(i, 0);
if (dataGridCell != null)
{
DataGridCellInfo dataGridCellInfo = new DataGridCellInfo(dataGridCell); if (dataGridCellInfo.Item != null)
{
object item = dataGridCellInfo.Item; FrameworkElement element = templeColumn.GetCellContent(item); if (element != null)
{
DataGrid dataGrid2 = (DataGrid)templeColumn.CellTemplate.FindName("DataGrid2", element);
dataGrid2.ItemsSource = characterlist;
}
}
}
}
} public DataGridCell GetDataGridCell(int rowIndex, int columnIndex)
{
try
{
DataGridRow rowContainer = GetDataGridRow(rowIndex);
if (rowContainer != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
//这行代码是通过行得到单元格 DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
//这行代码是通过index得到具体的单元格 if (cell == null)
{
DataGrid1.ScrollIntoView(rowContainer, DataGrid1.Columns[columnIndex]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
}
return cell;
}
}
catch
{
return null;
}
return new DataGridCell();
} public DataGridRow GetDataGridRow(int index)
{
if (index >= DataGrid1.Items.Count)
{
throw new IndexOutOfRangeException(String.Format("Index {0} is out of range.", index));
} DataGridRow row = (DataGridRow)DataGrid1.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
// may be virtualized, bring into view and try again
DataGrid1.ScrollIntoView(DataGrid1.Items[index]);
WaitFor(TimeSpan.Zero, DispatcherPriority.SystemIdle);
row = (DataGridRow)DataGrid1.ItemContainerGenerator.ContainerFromIndex(index);
} return row;
}
public void WaitFor(TimeSpan time, DispatcherPriority priority)
{
DispatcherTimer timer = new DispatcherTimer(priority);
timer.Tick += new EventHandler(OnDispatched);
timer.Interval = time;
DispatcherFrame dispatcherFrame = new DispatcherFrame(false);
timer.Tag = dispatcherFrame;
timer.Start();
Dispatcher.PushFrame(dispatcherFrame);
}
public void OnDispatched(object sender, EventArgs args)
{
DispatcherTimer timer = (DispatcherTimer)sender;
timer.Tick -= new EventHandler(OnDispatched);
timer.Stop();
DispatcherFrame frame = (DispatcherFrame)timer.Tag;
frame.Continue = false;
} public T GetVisualChild<T>(Visual parent) where T : Visual
{
T childContent = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
childContent = v as T;
if (childContent == null)
{
childContent = GetVisualChild<T>(v);
}
if (childContent != null)
{
break;
}
}
return childContent;
} private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
DataGridTemplateColumn templeColumn = DataGrid1.Columns[4] as DataGridTemplateColumn;
if (templeColumn == null) return; for (int i = 0; i < DataGrid1.Items.Count; i++)
{
DataGridCell dataGridCell = GetDataGridCell(i, 0);
if (dataGridCell != null)
{
DataGridCellInfo dataGridCellInfo = new DataGridCellInfo(dataGridCell); if (dataGridCellInfo.Item != null)
{
object item = dataGridCellInfo.Item; FrameworkElement element = templeColumn.GetCellContent(item); if (element != null)
{
DataGrid dataGrid2 = (DataGrid)templeColumn.CellTemplate.FindName("DataGrid2", element);
dataGrid2.ItemsSource = characterlist; DataGridRow row = (DataGridRow)dataGrid2.ItemContainerGenerator.ContainerFromIndex(2);
row.Visibility = Visibility.Collapsed;
}
}
}
}
}
} public class Person
{
public int id { get; set; }
public string name { get; set; }
public int age { get; set; } public int TotalCount { get; set; }
} public class Character
{
public string name { get; set; }
}
}

效果图:

点击TextBox后再点击DataGrid效果图:

C# DataGrid嵌套DataGrid动态隐藏显示行的更多相关文章

  1. table 动态隐藏tr行

    table: <table style="width:100%" class="table01" cellspacing="1" ce ...

  2. Android 动态隐藏显示导航栏,状态栏

    Talk is cheap, show me the code. --Linus Torvalds Okay, here: 一.导航栏: [java] view plain copy private  ...

  3. 动态隐藏显示窗口的标题栏(同时保持窗口的sizeable性能

    今天考虑作界面的时候,想去掉窗体的标题栏,但设置 Form.BorderStyle := bsNone; 会导致窗体不可再 Sizeable (通过鼠标操作改变窗体大小),仔细翻看了相关Help也没找 ...

  4. easyui datagrid 表格动态隐藏部分列的展示

    1.一套代码中,可能不同的项目情况都在用,但是可能不同的项目要求展示的datagrid列的内容并不一致,所以能够动态的显示部分datagrid列的内容. 即datagrid的中的某一列,这个项目要求显 ...

  5. Easy DataGrid 实现动态列、行

    Easy DataGrid 实现动态列.行 前端代码: <title>展示销售的实时数据</title> <script type="text/javascri ...

  6. Easyui Datagrid 修改显示行号列宽度

    EasyUI中Datagrid的第一列显示行号,可是如果数据量大的的时候,显示行号的那一列数据会显示不完全的. 可以通过修改Datagrid的样式来解决这个问题,在样式中加入下面这个样式,就可以自己修 ...

  7. 重新=》easyui DataGrid是否可以动态的改变列显示的顺序

    $.extend($.fn.datagrid.methods,{ columnMoving: function(jq){ return jq.each(function(){ var target = ...

  8. 实现easyui datagrid在没有数据时显示相关提示内容

    本示例实现easyui datagrid加载/查询数据时,如果没有相关记录,则在datagrid中显示没有相关记录的提示信息,效果如下图所示 本实例要实现如下图所示的效果: 本示例easyui版本为1 ...

  9. easy ui datagrid在没有数据时显示相关提示内容

    $(function () { $('#dg').datagrid({ fitColumns: true, url: 'product.json', pagination: true, pageSiz ...

  10. 经历:easyui的datagrid没有数据滚动条的显示

    今天,一个用户提出一个这样的问题,"查询不到结果时,为什么我看不到后面的标题呢?" 最初,我听到这个问题时,第一反应是:查出来数据不就有滚动条了吗,干嘛非要较真呢? 不过,后来想想 ...

随机推荐

  1. ArcGIS for Android 开发环境搭建

    ArcGIS for Android 开发环境搭建 1. 基础环境搭建 1.1. 安装JDK 安装JDK8,并设置环境变量 在cmd窗口输入java -version检查是否配置完成 java -ve ...

  2. PostgreSQL性能优化综合案例 - 2

    [调优阶段8] 1. 压力测试 pgbench -M prepared -r -c 1 -f /home/postgres/test/login0.sql -j 1 -n -T 180 -h 172. ...

  3. .Babylon格式的模型转化为glb模型,并使用ThreeJS加载显示

    问题描述:手里有几个.babylon格式的三维模型,但是没用过babylon,只对ThreeJS熟悉:但是最新的ThreeJS里发现已经没有BabylonLoader的加载器,能查到的暮志未晚提供的例 ...

  4. Day 13 13.3 Cookie与Session

    Cookie 一.什么是cookie? cookie的本质就是一组数据(键值对的形式存在) 是由服务器创建,返回给客户端,最终会保存在客户端浏览器中. 如果客户端保存了cookie,则下次再次访问该服 ...

  5. TypeError: 'int' object is not subscriptable 报错

    Python中报错TypeError: 'int' object is not subscriptable 原因:整形数据中加了下标索引 例如 #python utf-8 a = 10 b = a[0 ...

  6. MATLAB批量处理表格类型文件

    MATLAB版本2020b 问题背景:预处理数据,有若干变压器温度表格,要将变压器运行温度数据提取出来 通过LSTM模型进行温度预测

  7. scrapy_redis 分布式爬取酷狗音乐

    目录 声明 安装scrapy_redis 创建scrapy项目 spider模块 items模块.pipelines模块 setting.py 调试 运行 成果图 源码 声明 文章仅供学习交流使用,切 ...

  8. Django基础(1)

    一.开发模式 MVC模式: model:数据库 view:前端展示 controller:逻辑控制 MTV模式(Django): model:数据库 view:逻辑控制 template:前端展示(模 ...

  9. junit使用进阶

    一.模拟http请求测试接口 新建一个controller @RestController public class AATestController { @GetMapping("/tes ...

  10. C++ 手动实现栈(stack) (课后作业版)

    栈,一种遵循先进先出原则的数据结构,可以用顺序表实现,也可以用链表进行实现. 这里我使用数组实现方法,包含了进栈,出栈,访问栈顶等功能,以及一些辅助功能. 栈Stack类定义如下: template ...