【问题标题】:how to dynamically add button to SilverLight datagrid如何将按钮动态添加到 SilverLight 数据网格
【发布时间】:2010-03-16 01:23:23
【问题描述】:

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

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对应的参数的点击事件...

【问题讨论】:

    标签: silverlight-3.0


    【解决方案1】:

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

    【讨论】:

    • 是的,如果有一种“非时髦”的方式,我当然愿意这样做!没有 datagrid.children 命名空间,但是......你能提供一些代码吗? (我已经读过要动态添加按钮,您必须执行我上面所做的操作;尽管 SL3 可能会有所改变)
    【解决方案2】:

    好的,您必须在加载每一行时附加事件!因此,将以下内容附加到您的 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);
                    }
                }
            }
    

    【讨论】:

      猜你喜欢
      • 2010-09-29
      • 2011-10-23
      • 2010-12-15
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-18
      相关资源
      最近更新 更多