2010-03-16 144 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