轉帖|使用教程|編輯:龔雪|2016-05-27 09:37:30.000|閱讀 1205 次
概述:對于C1FlexGrid,如何給單元格設置樣式(包括前景色,背景色)是提出最多的問題。本文就通過示例介紹如何給C1FlexGrid設置特定單元格的樣式。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
<ComponentOne Studio for WPF下載>
對于C1FlexGrid,如何給單元格設置樣式(包括前景色,背景色)是提出最多的問題。本文就通過示例介紹如何給C1FlexGrid設置特定單元格的樣式。通常情況,我們通過C1FlexGrid的CellFactory實現樣式的設置,通過重寫ApplyCellStyles方法來實現。
首先,我們需要對c1flexgrid進行數據綁定顯示數據。在這里,我們假設綁定一個DataTable,代碼如下:
DataTable dt = new DataTable(); dt.Columns.Add("CurrencyCode", typeof(int)); dt.Columns.Add("Industry", typeof(string)); dt.Columns.Add("Market", typeof(string)); dt.Columns.Add("Sector", typeof(int)); dt.Columns.Add("Total", typeof(double)); dt.Columns.Add("SecurityType", typeof(string)); dt.Rows.Add(1, "Ind1", "M1", 100, null, "type1"); dt.Rows.Add(2, "Ind2", "M2", 200, null, "type2"); dt.Rows.Add(3, "Ind3", "M3", 300, 12345678.1234567, "type3"); dt.Rows.Add(4, "Ind4", "M4", 400, 12345678.1234567, "type4"); dt.Rows.Add(5, "Ind5", "M5", 500, 12345678.1234567, "type5"); dt.Rows.Add(6, "Ind6", "M6", 600, 12345678.1234567, "type6"); dt.Rows.Add(7, "Ind7", "M7", 700, 12345678.1234567, "type7"); dt.Rows.Add(8, "Ind8", "M8", 800, 12345678.1234567, "type8"); dt.Rows.Add(9, "Ind9", "M9", 900, 12345678.1234567, "type9"); flex.ItemsSource = dt.AsDataView();
自定義一個MyCellFactory類繼承CellFactory,并且設置給C1FlexGrid。代碼如下:
flex.CellFactory = new MyCellFactory();
通過重寫CellFactory的ApplyCellStyles方法,來實現指定單元格的樣式設置。通過bdr拿到單元格的TextBlock,并且設置TextBlock的文字樣式(比如FontWeight,FontSize)。以及bdr設置背景色。代碼參考:
public override void ApplyCellStyles(C1FlexGrid grid, CellType cellType, CellRange range, Border bdr) { var columnindex = range.Column; var rowindex = range.Row; if ((columnindex == 2) && (rowindex == 3)) { //set the customizations on the cell when it is not selected bdr.Background = new SolidColorBrush(Colors.Red); bdr.BorderBrush = Brushes.Blue; bdr.BorderThickness = new Thickness(1); } }
這個時候運行代碼,就發現column=2, row=3的單元格的樣式已經改變,如圖:
這個時候樣式已經設置完成。但是當選擇到指定的單元格的時候,這個樣式會保持不變。有的用戶就希望原本的Selection 的樣式能夠保留。我們通過改進代碼來實現這個需求:這個時候,我們需要添加一個判斷條件,來判斷指定單元格是否被選擇。判斷條件:
if (columnindex == grid.Selection.Column && rowindex == grid.Selection.Row)
如果指定單元格被選擇,就將背景色設置為選擇背景色。這個時候的改進方法如下:
public override void ApplyCellStyles(C1FlexGrid grid, CellType cellType, CellRange range, Border bdr) { var columnindex = range.Column; var rowindex = range.Row; //check if the cell is selected or not if ((columnindex == 2) && (rowindex == 3)) { if (columnindex == grid.Selection.Column && rowindex == grid.Selection.Row) { //set a different backcolor and border brush //when the cell is selected //leave the remaining customizations as it is bdr.Background = grid.SelectionBackground; } else { bdr.Background = new SolidColorBrush(Colors.Red); bdr.BorderBrush = Brushes.Blue; bdr.BorderThickness = new Thickness(1); } } }
至此,就實現了指定單元格的背景色設置。
本文的示例請下載:
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:慧都控件網