2010-03-16 171 views
0

我有一个数据网格,我想在运行时添加一个按钮。我设法用下面的代码做到这一点:如何动态添加按钮到SilverLight数据网格

DataGridTemplateColumn templateCol = new DataGridTemplateColumn(); 
templateCol.CellTemplate = (System.Windows.DataTemplate)XamlReader.Load(
    @"<DataTemplate xmlns='http://schemas.microsoft.com/client/2007' 
    xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'> 
    <Button Content='" + item.Value.Label + @"'/> 
    </DataTemplate>"); 

_dataGrid.Columns.Add(templateCol); 

问题是,我不能解决如何添加一个点击事件。我想添加一个单击事件与参数对应的行ID ...

回答

0

好吧,您必须在加载每一行时附加事件!因此,附加以下到您LoadingRow事件......

private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e) 
     { 
      DataGridRow row = e.Row; 
      foreach (DataGridColumn col in _dataGrid.Columns) 
      { 
       FrameworkElement cellContent = col.GetCellContent(e.Row); 
       Button b = cellContent as Button; 
       if (b != null) 
       { 
        //clear previous event 
        b.Click -= ActionButton_Click; 

        b.Click += new RoutedEventHandler(ActionButton_Click); 
       } 
      } 
     } 
0

这似乎是一种有点时髦的方式来做到这一点。我将实例化一个新按钮,将其设置为属性(包括grid.setcolumn)并将其添加到datagrid.children。如果您需要每个单元格中的按钮,都可以创建一个循环。

+0

是啊,如果有这样做的“非时髦”方式,我当然想这样做的!没有datagrid.children命名空间,但是...你能提供一些代码吗? (我已经读过,动态地添加一个按钮,你必须做我以上所做的事情;虽然事情可能已经改变了SL3) – 2010-03-16 03:03:35