首页 > 其他分享 >wpf dataGrid 获取单元格,并对单元格中的对象操作

wpf dataGrid 获取单元格,并对单元格中的对象操作

时间:2022-11-21 15:48:39浏览次数:51  
标签:Windows 单元格 System timer dataGrid new using wpf 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" Loaded="Window_Loaded">
    <Grid>
        <Grid.Resources>
                       
            <DataTemplate x:Key="DateTemplate" >
                <StackPanel DataContext="{Binding choseItems}">
                    <Border Background="LightBlue">
                        <TextBox Text="{Binding ChoseName}" Cursor="Arrow" Name="R0"/>
                    </Border>
                    <Border Background="White">
                        <TextBox Text="{Binding ChoseContent}" Cursor="Arrow" Name="R1"/>
                    </Border>
                </StackPanel>
            </DataTemplate>
            
            <DataTemplate x:Key="EditingDateTemplate">
                
            </DataTemplate>
        </Grid.Resources>


        <DataGrid AutoGenerateColumns="False" Name="datagrid1">
            <DataGrid.Columns>
                <DataGridTextColumn Header="ID值"  Width="auto" Binding="{Binding questionID}" />
                <DataGridTextColumn Header="题目"  Width="auto" Binding="{Binding questionName}" />
                <DataGridTemplateColumn Header="多行" Width="*" MinWidth="25"                                         
                                        CellTemplate="{StaticResource DateTemplate}" CellEditingTemplate="{StaticResource EditingDateTemplate}" IsReadOnly="True"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

后端代码;

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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();
        }

        class question
        {
            //题目ID号
            public Int32 questionID { get; set; }

            //题目名,比如:第1题或第2题等
            public string questionName { get; set; }

            //某题中"选项类"的集合,比如A-D
            public ObservableCollection<choseItem> choseItems { get; set; }
            public question(Int32 _id, string _questionname, ObservableCollection <choseItem> _choseitems)//构造函数
            {
                questionID = _id;
                questionName = _questionname;
                choseItems = _choseitems;
            }
        }
        //选项类
        class choseItem
        {
                //选项名,比如:A,B,C,D之类
                public string ChoseName { get; set; }
                //选项内容
                public string ChoseContent { get; set; }
        }
        ObservableCollection <question> Questions = new ObservableCollection <question>();//题目数组

        ObservableCollection<choseItem> ChoseItems = new ObservableCollection<choseItem>();//选项数组

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string[] CharStr = new string[4] { "A", "B", "C", "D" };
            for (int i = 0; i < 5; i++)
            {                          
                for (int j = 0; j < 4; j++)
                {
                    choseItem item = new choseItem();//选项类
                    item.ChoseName = CharStr[j] + ":";
                    item.ChoseContent = "选项内容举例...";
                    ChoseItems.Add(item);
                }
                Questions.Add(new question(i, "__第" + (i + 1).ToString() + "题", ChoseItems));
            }
            datagrid1.ItemsSource = Questions;

            ShowChildCell(datagrid1, 2, 9);
        }

        public static void ShowChildCell(DataGrid datagrid, int colNum, int childCellCount = 9)
        {
            DataGridTemplateColumn templeColumn = datagrid.Columns[colNum] as DataGridTemplateColumn;
            if (templeColumn == null) return;

            DataGridCell dataGridCell = GetDataGridCell(datagrid, 0, colNum);
            DataGridCellInfo dataGridCellInfo = new DataGridCellInfo(dataGridCell);

            object item = dataGridCellInfo.Item;

            FrameworkElement element = templeColumn.GetCellContent(item);
            TextBox textBlockOther = (TextBox)templeColumn.CellTemplate.FindName("R1", element);

            textBlockOther.Visibility = Visibility.Hidden;
        }

        public static DataGridCell GetDataGridCell(DataGrid datagrid, int rowIndex, int columnIndex)
        {
            try
            {
                DataGridRow rowContainer = GetDataGridRow(datagrid, rowIndex);
                if (rowContainer != null)
                {
                    DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
                    //这行代码是通过行得到单元格

                    DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
                    //这行代码是通过index得到具体的单元格

                    if (cell == null)
                    {
                        datagrid.ScrollIntoView(rowContainer, datagrid.Columns[columnIndex]);
                        cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
                    }
                    return cell;
                }
            }
            catch
            {
                return null;
            }
            return new DataGridCell();
        }

        public static DataGridRow GetDataGridRow(DataGrid dataGrid, int index)
        {
            if (index >= dataGrid.Items.Count)
            {
                throw new IndexOutOfRangeException(String.Format("Index {0} is out of range.", index));
            }

            DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index);
            if (row == null)
            {
                // may be virtualized, bring into view and try again
                dataGrid.ScrollIntoView(dataGrid.Items[index]);
                WaitFor(TimeSpan.Zero, DispatcherPriority.SystemIdle);
                row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index);
            }

            return row;
        }
        public static 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 static 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 static 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;
        }
    }
}

 

标签:Windows,单元格,System,timer,dataGrid,new,using,wpf,public
From: https://www.cnblogs.com/wuguoqiang/p/16911546.html

相关文章

  • WPF 后台线程操作界面元素不卡UI界面线程 Dispatcher
    经常要考虑的,后台的耗时操作不要卡死主界面的问题。<StackPanelVerticalAlignment="Center"><Labelx:Name="lblHello">欢迎你光临WPF的世界!</Label><ButtonName......
  • WPF布局(Layout)
    StackPanel特点:子元素一行或者一列排列<StackPanelBackground="#ECE9D8">  <TextBlockMargin="3">Lookfor:</TextBlock>  <ComboBox Margin="3"/>  <TextBlo......
  • WPF-Layout
    StackPanel特点:子元素一行或者一列排列<StackPanelBackground="#ECE9D8">  <TextBlockMargin="3">Lookfor:</TextBlock>  <ComboBox Margin="3"/>  <TextBlo......
  • WPF只允许创建一个应用实例代码
    usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;usingSystem.Windo......
  • WPF-应用生命周期
    hehehhee呵呵呵......
  • 解决WPF中DataGrid移除选中项后报错的问题
    1、问题描述DataGrid列表中添加删除按钮,点击后执行下述操作:ModelList.Remove(item);这时候会有XAML绑定失败错误:严重性计数数据上下文绑定路径目标......
  • C# WPF 测试直接绑定依赖属性双向传递是没有问题的
    续这篇测试:https://www.cnblogs.com/huvjie/p/16909290.html测试页面:<Windowx:Class="MyWPFSimple3.MainWindow"xmlns="http://schemas.microsoft.com/winfx/......
  • WPF自定义控件之消息提示
    创建消息提示控件internalclassMessage:ContentControl{publicintTime{get;set;}[Bindable(true)]publicMessageTypeMes......
  • 【WPF】ComboBox控件
    ComboBox控件属性IsTextSearchEnabled="True":自动补充数据IsTextSearchCaseSensitive=true;自动补充数据,区分大小写IsDropDownOpen="True":combobox自动打开下拉框......
  • delphi TMS FlexCel 取消合并单元格
    TMSFlexCel取消合并单元格属性和方法TXlsFile.UnMergeCellsprocedureUnMergeCells(constfirstRow:Integer;constfirstCol:Integer;constlastRow:Integer;co......