Need to append edit field and button to grid cell programatically

WPF

Windows Presentation Foundation controls

Need to append edit field and button to grid cell programatically

  • rated by 0 users
  • This post has 1 Reply |
  • 0 Followers
  • I want a cell in my datagrid to contain and edit field AND a small button beside it in the same cell to the right. So far I've got the button there, but not sure how to get both there.  I need to do this in code. So far I have this for my button. Thanks for your help. Colleen

    FrameworkElement myButton = new Button();
    myButton.Width = 23;
    myButton.HorizontalAlignment =
    HorizontalAlignment.Right;
    FrameworkElementFactory buttonFactory = new FrameworkElementFactory(typeof(Button));
    buttonFactory.SetValue(Button.WidthProperty, myButton.Width);
    buttonFactory.SetValue(
    Button.HorizontalAlignmentProperty, myButton.HorizontalAlignment);

     

    ControlTemplate templButton = new ControlTemplate();
    FrameworkElementFactory rootButton = new FrameworkElementFactory(typeof(Border));

    rootButton.AppendChild(buttonFactory);
    templButton.VisualTree = rootButton;
    c1DataGrid1.Columns[0].ItemCellEditContentTemplate = templButton;

  • I found my answer for anyone looking for the same. I needed to create a StackPanel instead of a border attached to the cell:

    //Button and field in same cell

    TextBox myText = new TextBox();

    myText.Width = 50;

    myText.HorizontalAlignment =
    HorizontalAlignment.Left;

    FrameworkElementFactory textFactory = new FrameworkElementFactory(typeof(TextBox));

    textFactory.SetValue(TextBox.WidthProperty, myText.Width);

    textFactory.SetValue(TextBox.HorizontalAlignmentProperty, myText.HorizontalAlignment);

    Button myButton = new Button();

    myButton.Width = 23;

    myButton.HorizontalAlignment =
    HorizontalAlignment.Right;

    myButton.Margin = new Thickness(10, 0, 0, 0);

    FrameworkElementFactory buttonFactory = new FrameworkElementFactory(typeof(Button));

    buttonFactory.SetValue(Button.WidthProperty, myButton.Width);

    buttonFactory.SetValue(Button.HorizontalAlignmentProperty, myButton.HorizontalAlignment);buttonFactory.SetValue(Button.MarginProperty, myButton.Margin);

     

    StackPanel stackPanel = new StackPanel();

    stackPanel.Orientation = Orientation.Horizontal;

     

    FrameworkElementFactory rootPanel = new FrameworkElementFactory(typeof(StackPanel));rootPanel.SetValue(StackPanel.OrientationProperty, stackPanel.Orientation);

    rootPanel.AppendChild(textFactory);

    rootPanel.AppendChild(buttonFactory);

    templButton.VisualTree = rootPanel;

    c1DataGrid1.Columns[0].ItemCellEditContentTemplate = templButton;

     

Page 1 of 1 (2 items)