从代码隐藏的c#代码添加WPF数据网格行上的按钮

时间:2016-01-13 07:33:17

标签: c# .net wpf

我想在WPF网格的每一行上添加一个按钮,我从后面的代码绑定。我是WPF的新手,感谢任何帮助。

我目前绑定网格的代码是:

        DataGridTextColumn c1 = new DataGridTextColumn();
        c1.Header = "Dummy column";
        c1.Binding = new Binding("DummyColumn");
        c1.IsReadOnly = true;
        grdDummy.Columns.Add(c1);

        foreach (DummyObject deal in AllDummyObjects)
        {
            ModelToBind dataModel = new ModelToBind()
            //do some processing on dataModel

            grdDummy.Items.Add(dataModel);
        }

1 个答案:

答案 0 :(得分:0)

您可以使用以下按钮添加另一列:

    DataGridTemplateColumn buttonColumn = new DataGridTemplateColumn();
    DataTemplate buttonTemplate = new DataTemplate();
    FrameworkElementFactory buttonFactory = new FrameworkElementFactory(typeof (Button));
    buttonTemplate.VisualTree = buttonFactory;
    //add handler or you can add binding to command if you want to handle click
    buttonFactory.AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(HandleClick));
    buttonFactory.SetValue(ContentProperty, "Button");
    buttonColumn.CellTemplate = buttonTemplate;
    grdDummy.Columns.Add(buttonColumn);