通过Tag属性可以设置自定义的数据,使用GetCellContent方法可以到单元格内的控件,所以就可以得到你点击的是哪一行了。点击的操作就很容易了。
下面的是全部的源代码
Page,xaml
- using System;
- using System.Collections.Generic;
- using System.Windows;
- using System.Windows.Controls;
- namespace DataGridSnippets
- {
- public partial class Page : UserControl
- {
- public Page()
- {
- InitializeComponent();
- //绑定数据
- dataGrid1.ItemsSource = Customer.GetSampleCustomerList();
- }
- private void dataGrid1_LoadingRow(object sender, DataGridRowEventArgs e)
- {
- Customer bindData = (Customer)e.Row.DataContext;
- Button btn = dataGrid1.Columns[3].GetCellContent(e.Row).FindName("Button1") as Button;
- btn.Content = bindData.UserName;
- btn.Tag = bindData.IndexName + "," + e.Row.GetIndex();
- }
- private void Button1_Click(object sender, RoutedEventArgs e)
- {
- Button b = sender as Button;
- string[] t = b.Tag.ToString().Split(',');
- msg.Text = "你选择的值是:" + t[0] + " 是 DataGrid 的第 " + t[1] + " 行";
- }
- }
- /// <summary>
- /// 数据对象
- /// </summary>
- public class Customer
- {
- public Int32 IndexName { get; set; }
- public String UserName { get; set; }
- public String Address { get; set; }
- public Customer(Int32 indexName, String userName, String address)
- {
- this.IndexName = indexName;
- this.UserName = userName;
- this.Address = address;
- }
- public static List<Customer> GetSampleCustomerList()
- {
- //示例数据
- List<Customer> data = new List<Customer>();
- for(int i = 0;i<10;i++)
- {
- data.Add(new Customer(i*i, "孟宪会之" + i.ToString(), "地址之" + i.ToString()));
- }
- return data;
- }
- }
- }
本文基于Silverlight 2.0正式版。