如题:最近需要实现报表功能,用了vs2010自带的datagrid的控件,遇到一问题,为了实现在每一行后增加一列,在此列中实现编辑、删除、查看详细等操作。此种方式也提高了用户体验性和便捷性。
先把代码分享如下:(随便写的测试代码)
1、建立一个sl项目,在主页面添加datagrid控件,
2.编写datagrid控件样式
如下:
<sdk:DataGrid AutoGenerateColumns="false" Height="98" HorizontalAlignment="Left" Margin="154,62,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="353">
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn Header="名字" Binding="{Binding name}" />
<sdk:DataGridTextColumn Header="年龄" Binding="{Binding age}" />
<sdk:DataGridTextColumn Header="性别" Binding="{Binding sex}" />
<sdk:DataGridTemplateColumn Header=" 操作">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Content="删除"/>
<Button Content="修改"/>
<Button Content="详细" x:Name="btn_detail" Click="btn_detail_Click"/>
</StackPanel>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
3.后台测试代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace SilverlightApplication2
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
List<myclass> li = new List<myclass>();
myclass ml = new myclass();
ml.name = "张三";
ml.age = "11";
ml.sex = "女";
myclass ml2 = new myclass();
ml2.name = "李四";
ml2.age = "22";
ml2.sex = "男";
li.Add(ml);
li.Add(ml2);
//this.dataGrid1.Columns.Clear();
this.dataGrid1.ItemsSource = li;
}
/// <summary>
/// 详细
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_detail_Click(object sender, RoutedEventArgs e)
{
int a= this.dataGrid1.SelectedIndex;
object obj = this.dataGrid1.SelectedItem;
myclass mycla=(myclass)obj;
MessageBox.Show("当前选择行索引:"+a+"\n当前选择的信息:\n名字:"+mycla.name+"\n年龄:"+mycla.age+"\n性别:"+mycla.sex);
}
}
public class myclass
{
public string name
{
get; set;
}
public string age
{ get;set;}
public string sex
{ get; set; }
}
}