C#鼠标绘制表格模板
时间: 2024-09-23 13:09:36 浏览: 46
在C#中,你可以使用Windows Forms控件如DataGridView或者ListView来创建复杂的表格,它们已经包含了丰富的样式和功能,不需要手动绘制每个单元格。如果你需要自定义鼠标绘制表格,可以利用WPF(Windows Presentation Foundation)平台,特别是Canvas或ItemsControl配合DataTemplate,但这通常会涉及到更复杂的UI编程。
以下是使用WPF手动绘制表格的一个简单示例:
```csharp
using System.Windows;
using System.Windows.Controls;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// 创建数据源
var data = new List<Dictionary<string, object>>()
{
{{"Name", "John"}, {"Age", 30}, {"City", "New York"}},
{{"Name", "Jane"}, {"Age", 25}, {"City", "London"}}
};
// 渲染数据到Canvas
foreach (var row in data)
{
Canvas canvasRow = new Canvas();
for (int i = 0; i < row.Count; i++)
{
FrameworkElement cell = CreateTableCell(row[i].Key, row[i].Value);
canvasRow.Children.Add(cell);
canvasRow.Width = double.NaN; // 自动调整宽度
}
Grid.SetColumn(canvasRow, i); // 设置行数
grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto }); // 添加一行
grid.Children.Add(canvasRow);
}
}
private FrameworkElement CreateTableCell(string header, object value)
{
TextBlock headerText = new TextBlock { Text = header };
TextBlock valueText = new TextBlock { Text = value.ToString() };
// 根据需求定制单元格样式,比如添加边框、改变颜色等
Border border = new Border { BorderBrush = Brushes.Black, BorderThickness = new Thickness(1) };
border.Child = new StackPanel { Orientation = Orientation.Horizontal,
Children = {headerText, valueText} };
return border;
}
}
```
阅读全文