JamTay317
JamTay317

Reputation: 1017

Adding an event or command to DataGridTextColumn

I am adding a Custom DataGridTextColumn that will allow me to fire an event when when ever the content is changed in this cell.

Please note:

I do not want to use a DataGridTemplateColumn with this as I know that. I want to create my own text column as there are a lot of features that come with text column that we use.

So I decided to just simply add an event to a custom control - simple enough. not so much. well it seams that there isn't an AddHandler or RemoveHandler methods.

Please explain where I am going wrong.

Code:

public static readonly RoutedEvent TextChangedEvent =
EventManager.RegisterRoutedEvent("TextChanged", RoutingStrategy.Bubble,
    typeof (RoutedEventHandler),
    typeof (DataGridTextChangedEventColumn));

public event RoutedEventHandler TextChanged
{
    add { AddHandler(TextChangedEvent, value); }
    remove { RemoveHandler(TextChangedEvent, value); }
}

private void AddHandler(RoutedEvent textChangedEvent, RoutedEventHandler value)
{
    this.TextChanged += (s, e) => textChangedEvent;
}

Thank you.

Upvotes: 3

Views: 1613

Answers (1)

Babbillumpa
Babbillumpa

Reputation: 1864

If you want to create "Your" customized DatagridTextColumn, you could create a CustomControl that inherits from DataGridTextColumn.

Doing this, you can override the method "GenerateEditingElement" that returns the control that is associated with the editing look of the grid (generally it is a TextBox).

While you are overriding this method, you can attach an event handler to Your TextChanged event.

public class YourCustomDataGridTextColumn : DataGridTextColumn
{


public delegate void ColumnTextChangedHandler(object sender,TextChangedEventArgs e);
public event ColumnTextChangedHandler ColumnTextChanged;

    #region "Methods"

    protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
    {
        var textBox = (TextBox)base.GenerateEditingElement(cell, dataItem);
        textBox.TextChanged += OnTextChanged;

        return textBox;
    }

    private void OnTextChanged(object sender, TextChangedEventArgs e)
    {
        //Your event handling
        if (ColumnTextChanged != null) {
                ColumnTextChanged(sender, e);
          }
    }

    #endregion    
}

Upvotes: 1

Related Questions