日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

C# WPF DataGrid获取单元格并改变背景色

發布時間:2023/12/4 C# 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C# WPF DataGrid获取单元格并改变背景色 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

01

概述

WPF 自帶了一個表格控件datagrid,這個控件類似winfrom中的datagridview,在數據顯示的時候也經常會用到,這節主要講解如何從后臺代碼獲取到單元格控件并改變其相關屬性:背景色、前景色、字體等。

02


效果演示

03


代碼

后臺cs:

using System; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Media;namespace Caliburn.Micro.Hello {/// <summary>/// ShellView.xaml 的交互邏輯/// </summary>public partial class ShellView : UserControl{public ShellView(){InitializeComponent();}private void DG_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e){int colindex = -1;int rowindex = -1;//方法1//DataGridCellInfo info = new DataGridCellInfo(dg.Items[0], dg.Columns[2]);//方法2//foreach (DataGridCellInfo info in this.dgSourceData.SelectedCells)//{// string str = ((TextBlock)info.Column.GetCellContent(info.Item)).Text;// Console.WriteLine(str);//}//方案1var info = this.dgSourceData.SelectedCells.FirstOrDefault();var str = ((TextBlock)info.Column.GetCellContent(info.Item)).Text;//((TextBlock)info.Column.GetCellContent(info.Item)).Foreground = new SolidColorBrush(Colors.Red);//Console.WriteLine(str);//方案2colindex = this.dgSourceData.CurrentCell.Column.DisplayIndex;//獲取選中單元格列號//rowindex = this.dgSourceData.SelectedIndex;//獲取選中單元格行號for (int i = 0; i < ShellViewModel.StudentList.Count(); i++){if (ShellViewModel.StudentList[i] == this.dgSourceData.CurrentItem){//MessageBox.Show("當前選擇的行是:" + i.ToString());rowindex = i;}}DataGridRow row = (DataGridRow)dgSourceData.ItemContainerGenerator.ContainerFromIndex(rowindex);//獲取選中單元格所在行DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);//函數調用,獲取行中所有單元格的集合DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(colindex);//鎖定選中單元格(重點)if (cell != null){TextBlock tb = cell.Content as TextBlock;Console.WriteLine(tb.Text);dgSourceData.ScrollIntoView(row, dgSourceData.Columns[colindex]);//cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(colindex);cell.Focus();cell.Background = new SolidColorBrush(Colors.Red);//OK!問題解決,選中單元格變色cell.Foreground = new SolidColorBrush(Colors.Yellow);cell.FontSize = 20;}}private void dgSourceData_BeginningEdit(object sender, DataGridCellEditEndingEventArgs e){}/// <summary>/// 獲取父可視對象中第一個指定類型的子可視對象/// </summary>/// <typeparam name="T">可視對象類型</typeparam>/// <param name="parent">父可視對象</param>/// <returns>第一個指定類型的子可視對象</returns>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;}public void dgSourceData_SelectionChanged(object sender, SelectionChangedEventArgs e){MessageBox.Show(1111.ToString());//SelectionMode="Extended" SelectionUnit="Cell" 模式下觸發不了}} }

前臺xaml:

<DataGrid Name="dgSourceData" AutoGenerateColumns="False" ItemsSource="{Binding StudentList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" ContextMenu="{Binding menu1}" RowHeaderWidth="30" SelectedItem ="{Binding SelectedItems}" SelectionMode="Single" SelectionUnit="Cell"cal:Message.Attach="[Event SelectionChanged]=[GridControl_SelectionChanged($source,$eventArgs)];" SelectedCellsChanged="DG_SelectedCellsChanged" CellEditEnding="dgSourceData_BeginningEdit" SelectionChanged="dgSourceData_SelectionChanged" ><DataGrid.Columns><DataGridTextColumn Header="Name" Binding="{ Binding Path=Name,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" MinWidth="68"/><DataGridTextColumn Header="Age" Binding="{ Binding Path=Age,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" MinWidth="68"/><DataGridTextColumn Header="Id" Binding="{ Binding Path=Id,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" MinWidth="48"/></DataGrid.Columns></DataGrid>

04


解析

① 因為我需要綁定SelectedCellsChanged事件,所以前臺將默認的行選中模式修改為單元格選中模式:

SelectionMode="Single" SelectionUnit="Cell"

這樣修改后SelectionChanged這個事件將不再觸發(只有在行選中模式下生效);

②獲取選中單元格的值:

var info = this.dgSourceData.SelectedCells.FirstOrDefault();var?str?=?((TextBlock)info.Column.GetCellContent(info.Item)).Text;

③獲取選中的列號:

colindex = this.dgSourceData.CurrentCell.Column.DisplayIndex;//獲取選中單元格列號

④獲取選中行的行號

在SelectionUnit="FullRow"?時候:

可以通過這樣獲取:

rowindex = this.dgSourceData.SelectedIndex;//獲取選中單元格行號

在當SelectionUnit="Cell"時:

我是通過選中單元格對應行的信息和表格控件綁定的集合匹配獲取行號的:

for (int i = 0; i < ShellViewModel.StudentList.Count(); i++){if (ShellViewModel.StudentList[i] == this.dgSourceData.CurrentItem){//MessageBox.Show("當前選擇的行是:" + i.ToString());rowindex = i;}}

⑤獲取選中單元格并改變字體顏色:

var?info?=?this.dgSourceData.SelectedCells.FirstOrDefault();var?str?=?((TextBlock)info.Column.GetCellContent(info.Item)).Text;((TextBlock)info.Column.GetCellContent(info.Item)).Foreground?=?new?SolidColorBrush(Colors.Red);

05


源碼下載

網盤下載鏈接:https://pan.baidu.com/s/1TD2BT5hiT-z-_7Z2Bn3PVQ

提取碼:添加小編微信獲取

技術群:添加小編微信并備注進群

小編微信:mm1552923 ??

公眾號:dotNet編程大全? ? ??

總結

以上是生活随笔為你收集整理的C# WPF DataGrid获取单元格并改变背景色的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。