当前位置:网站首页>C# WPF从后台代码生成行列可变的表格
C# WPF从后台代码生成行列可变的表格
2022-06-09 22:49:00 【用户9127601】
z概述
WPF常用的表格控件是DataGrid,这个控件在前台XAML编写的话,一般列已经固定,然后给每个列去绑定数据,但是如果我的列不固定,随着运算结果变动呢?这时候DataGrid,就比较难实现这个需求,这节我就从后台代码去添加控件去实现这个功能.
效果演示
实现方法
-. 前台XAML:
<dxlc:LayoutControl>
<Grid HorizontalAlignment="Left" VerticalAlignment="Top"
cal:Message.Attach="[Event Loaded]=[Grid_Loaded($source,$eventArgs)]" />
</dxlc:LayoutControl>这里我把grid放到了dxlc:LayoutControl中,这样可以实现grid尺寸超出界面分配的长宽时,横纵出现滑动条:如下图
-.后台代码:
数据模型:
public class WidthMetrologyDTO
{
/// <summary>
///
/// </summary>
public bool IsMeasureSuccess { get; set; }
/// <summary>
///
/// </summary>
public double Degree { get; set; }
/// <summary>
///
/// </summary>
public string ImageFilePath { get; set; }
/// <summary>
///
/// </summary>
public double Width { get; set; }
public double EdgeNum { get; set; }
public List<EdgePosition> EdgePositions { get; set; }
}
public class EdgePosition
{
public double EdgesAmplitude { get; set; }
}①定义grid以及数据集合:
public Grid resultDisplayGrid;
public BindableCollection<WidthMetrologyDTO> WidthMetrologyData { get; set; }
= new BindableCollection<WidthMetrologyDTO>();②控件加载时获取grid对象:
public void Grid_Loaded(object sender, RoutedEventArgs e)
{
resultDisplayGrid = (Grid)sender;
}③添加数据集合:
public void ResultDispaly()
{
try
{
WidthMetrologyData.Clear();
WidthMetrologyData.Add(new WidthMetrologyDTO
{
Width = 345.1,
EdgeNum = 3,
EdgePositions = new List<EdgePosition>
{
new EdgePosition(){EdgesAmplitude = 1.1},
new EdgePosition(){EdgesAmplitude = 2.2},
new EdgePosition(){EdgesAmplitude = 3.3},
},
});
WidthMetrologyData.Add(new WidthMetrologyDTO
{
Width = 345.2,
EdgeNum = 2,
EdgePositions = new List<EdgePosition>
{
new EdgePosition(){EdgesAmplitude = 4.4},
new EdgePosition(){EdgesAmplitude = 5.5},
},
});
WidthMetrologyData.Add(new WidthMetrologyDTO
{
Width = 345.3,
EdgeNum = 4,
EdgePositions = new List<EdgePosition>
{
new EdgePosition(){EdgesAmplitude = 6.6},
new EdgePosition(){EdgesAmplitude = 7.7},
new EdgePosition(){EdgesAmplitude = 8.8},
new EdgePosition(){EdgesAmplitude = 9.9},
},
});
WidthMetrologyData.Add(new WidthMetrologyDTO
{
Width = 345.0,
EdgeNum = 1,
EdgePositions = new List<EdgePosition>
{
new EdgePosition(){EdgesAmplitude = 0.66},
},
});
AddResultGrid();
}
catch (Exception ex)
{
//logger.Debug($"ResultData add fail : {ex}");
}
}④数据表格生成
public void AddResultGrid()
{
try
{
resultDisplayGrid.Children.Clear();
var gridColumns = 2 + WidthMetrologyData.OrderByDescending(index => index.EdgePositions.Count).FirstOrDefault().EdgePositions.Count;
var gridRows = 16;
//添加grid行
for (int i = 0; i < gridColumns; i++)
{
var columnDefinition = new ColumnDefinition();
resultDisplayGrid.ColumnDefinitions.Add(columnDefinition);
if (i == 1)
{
columnDefinition.Width = new GridLength(2, GridUnitType.Star);//相对尺寸
}
else
{
columnDefinition.Width = new GridLength(1, GridUnitType.Star);
}
//columnDefinition.Width = GridLength.Auto;
}
//添加grid列
for (int i = 0; i < gridRows; i++)
{
var rowDefinition = new RowDefinition();
resultDisplayGrid.RowDefinitions.Add(rowDefinition);
rowDefinition.Height = new GridLength(30, GridUnitType.Pixel);//绝对尺寸
}
//添加数据
//var controlWidth = 100;
//var controlHeight = 30;
for (int degreeIndex = 0; degreeIndex < WidthMetrologyData.Count; degreeIndex++)
{
var rowsCount = 3;
var columnsCount = WidthMetrologyData[degreeIndex].EdgePositions.Count;
for (int row = 0; row < rowsCount; row++)
for (int column = 0; column < columnsCount + 2; column++)
{
TextBlock tb = new TextBlock();
//tb.Width = controlWidth;
//tb.Height = controlHeight;
//tb.HorizontalAlignment = HorizontalAlignment.Left;
//tb.VerticalAlignment = VerticalAlignment.Center;
Border border = new Border();
border.BorderBrush = System.Windows.Media.Brushes.BlueViolet;
border.BorderThickness = new Thickness(1);
border.Child = tb;
border.SetValue(Grid.RowProperty, row + degreeIndex * 4);
border.SetValue(Grid.ColumnProperty, column);
resultDisplayGrid.Children.Add(border);
if (row == 0 && column >= 2)
{
tb.Text = (column - 1).ToString();
}
else if (row == 1 && column >= 2)
{
tb.Text = WidthMetrologyData[degreeIndex].EdgePositions[column - 2].EdgesAmplitude.ToString();
}
else if (row == 2 && column >= 2)
{
if (column == 2)
{
tb.Text = WidthMetrologyData[degreeIndex].Width.ToString();
//tb.Width = columnsCount * controlWidth;
tb.SetValue(Grid.ColumnSpanProperty, columnsCount);
}
else
{
continue;
}
}
if (column == 0)
{
if (row == 0)
{
switch (degreeIndex)
{
case 0:
tb.Text = "第一组"; break;
case 1:
tb.Text = "第二组"; break;
case 2:
tb.Text = "第三组"; break;
case 3:
tb.Text = "第四组"; break;
default: break;
}
//tb.Height = 3 * controlHeight;
tb.SetValue(Grid.RowSpanProperty, 3);
}
else
{
continue;
}
}
if (column == 1)
{
switch (row)
{
case 0:
tb.Text = "ID"; break;
case 1:
tb.Text = "Value"; break;
case 2:
tb.Text = "Fraction"; break;
default:
tb.Text = string.Empty; break;
}
//tb.Width = controlWidth;
}
}
}
resultDisplayGrid.Width = (gridColumns + 1)* 40;
//resultDisplayGrid.Height = gridRows * controlHeight;
}
catch (Exception ex)
{
//logger.Error($"Add result grid fail,{ex}");
}
}解释:
-. grid添加行以及尺寸设置:ridUnitType.Pixel代表绝对尺寸,GridUnitType.Star相对尺寸
var rowDefinition = new RowDefinition();
resultDisplayGrid.RowDefinitions.Add(rowDefinition);
rowDefinition.Height = new GridLength(30, GridUnitType.Pixel);//绝对尺寸自动尺寸:
columnDefinition.Width = GridLength.Auto;-. link的使用:按照集合中EdgePositions数量降序排列后获取第一个列表值
WidthMetrologyData.OrderByDescending(index => index.EdgePositions.Count).FirstOrDefault().EdgePositions.Count;-.生成控件并添加到grid中,并通过SetValue设置控件在grid中的行列位置
TextBlock tb = new TextBlock();
//tb.Width = controlWidth;
//tb.Height = controlHeight;
//tb.HorizontalAlignment = HorizontalAlignment.Left;
//tb.VerticalAlignment = VerticalAlignment.Center;
Border border = new Border();
border.BorderBrush = System.Windows.Media.Brushes.BlueViolet;
border.BorderThickness = new Thickness(1);
border.Child = tb;
border.SetValue(Grid.RowProperty, row + degreeIndex * 4);
border.SetValue(Grid.ColumnProperty, column);
resultDisplayGrid.Children.Add(border);源码
链接:https://pan.baidu.com/s/1mgzyTRVwvq1XpJ6y0iyVww
提取码:6666
边栏推荐
- Two tower model - Semantic Indexing Strategy [in batch negatives]
- 不能在此路径中使用此配置节,如果在父级别上锁定了该节,便会出现这种情况的解决办法
- Chaîne - 4 - 242. Mots hétérotopiques alphabétiques valides
- 堆叠线缆的光模块与普通光模块区别
- Openharmony risc-v lightweight system porting - shared with w800 porting
- JG file upload code and export Excel
- Getting to know websocket
- This configuration section cannot be used in this path. If the section is locked at the parent level, the solution to this situation will occur
- Getting started with Emu8086
- 2022 practice questions and mock exam of quality controller municipal direction general basic (quality controller) examination
猜你喜欢

Mazhiqiang: research progress and application of speech recognition technology -- RTC dev Meetup

微机原理与接口技术习题1
Deploy MySQL based on statefulset in kubernetes (Part 1)

致广大、尽精微,曙光问道算力服务“神经系统”

This configuration section cannot be used in this path. If the section is locked at the parent level, the solution to this situation will occur

牛客网:数据流中的中位数

Online JSON to CSV tool

蓝桥杯_分割立方体_组合数学_加法原理

Explanation of leetcode UHF questions (III)

15 provinces publish the average wage in 2021, and these industries have "money paths"
随机推荐
How to pass the probation period for new programmers
Orange Pie H3 burning uboot, remote loading zimage, DTB, rootfs
[JMeter] JMeter from introduction to mastery
Is Hebei Hengyin futures a regular platform? Is it safe?
[question brushing] jumping game
Introduction à Tencent - ncnn
心研手环实现情绪可视化,“让心可见”成为现实
What is a distributed software system
Implementation of ngnix dynamic reading environment variables
荐书 | 手牵手一步两步望着天,看星星一颗两颗连成线
记一次应急排查'新'路历程
2022 love analysis · privacy computing vendor panoramic report | love Analysis Report
Still doubting the digital collection? The national team is starting to get in
不能在此路径中使用此配置节,如果在父级别上锁定了该节,便会出现这种情况的解决办法
How to record the login information of accessing the database in oracle?
STM32驱动继电器 STM32F103RCT6基于寄存器和库函数驱动IO口
Online JSON to CSV tool
Explanation of leetcode UHF questions (III)
Implementation of online recruitment system based on JSP
Game installation, downloading and updating no unveils the mystery of future games