首页 > 编程语言 >C# DataGrid动态隐藏显示行

C# DataGrid动态隐藏显示行

时间:2022-12-05 11:55:35浏览次数:42  
标签:DataGrid1 C# System 隐藏 DataGrid new using null public

前端代码:

<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效果图:

 

标签:DataGrid1,C#,System,隐藏,DataGrid,new,using,null,public
From: https://www.cnblogs.com/wuguoqiang/p/16951909.html

相关文章

  • Meilisearch
    MeilisearchUsagecat>docker-compose.yml<<-'EOF'#https://docs.meilisearch.com/learn/getting_started/quick_start.html#setup-and-installation#Port:7700v......
  • 在doccker里面安装有头浏览器--实现跑自动化可以查看ui交互--(有空了解下)
    https://mp.weixin.qq.com/s/oUFF1_0ygwEyY8X-cg6g0Q看到这个,大家应该也毕竟熟悉了,其实就是Docker的NoVnc的镜像,图形界面化docker环境,用浏览器直接打开就可以看到桌面,还可......
  • vs 使用第三方库配置jsoncpp
    https://blog.csdn.net/hml111666/article/details/127227992?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendF......
  • PCIE 上位机 介绍
    本文为明德扬原创文章,转载请注明出处!开发环境:windows开发平台:QT5.11.31、PCIE上位机测试过程FPGA将数据传到芯片中,通过pcie再将芯片算完的数传给上位机。目标:1.实现上位机的......
  • JAVASCRIPT数组小结
    ​数组是值的有序集合。每个值叫做一个元素,而每个元素在数组中有一个位置,以数字表示,称为索引。JavaScript数组是无类型的,数组元素可以是任意类型,并......
  • pytorch中调整学习率的方法
    1.lr_scheduler.StepLRclasstorch.optim.lr_scheduler.StepLR(optimizer,step_size,gamma=0.1,last_epoch=-1)功能: 等间隔调整学习率,调整倍数为gamma倍,调整间隔为st......
  • 在c#中调用c++的dll崩溃了,try catch 怎么获取异常?
    在framework框架下,通过添加HandleProcessCorruptedStateExceptionsAttribute属性来解决这个问题,(.netcore1.0到3.1之前,不支持从损坏的进程状态异常中恢复,即trycatch没有......
  • SiteFactory支持pdf自动导入
    ​图片的复制无非有两种方法,一种是图片直接上传到服务器,另外一种转换成二进制流的base64码目前限chrome浏览器使用首先以um-editor的二进制流保存为例:打开umeditor.js,......
  • C++ IMPL模式解析(下)
    二进制兼容在上一章结尾处提到了二进制兼容的概念,这里先说说二进制兼容的问题。为什么是二进制兼容简单说,就是我的可执行程序调用你的动态库(so/dll),若动态库发生改动,我......
  • 必须关闭ECACEH的这个后门
    今天偶然才发现,日志中ECACHE有报错:{INFO}[2014-06-3007:42:10,625]<net.sf.ehcache.util.UpdateChecker>:Newupdate(s)found:2.6.5[http:/......