开发者

Overriding DataGridTextColumn

I am trying to provide a DataGrid column that behaves like the DataGridTextColumn, but with an additional button in editing mode. I looked at DataGridTemplateColumn, but it appears easier to subclass the DataGridTextColumn as below

The problem is the textBox loses its binding when added to the grid. That is, changes to its Text property are not reflected in the non-editing TextBlock or the underlying view-mode

Any thoughts on why this might be and how I can work around it?

public class DataGridFileColum开发者_高级运维n : DataGridTextColumn
{
    protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
    {
        TextBox textBox = (TextBox)base.GenerateEditingElement(cell, dataItem);

        Button button = new Button { Content = "..." };
        Grid.SetColumn(button, 1);

        return new Grid
        {
            ColumnDefinitions = {
                new ColumnDefinition(),
                new ColumnDefinition { Width = GridLength.Auto },
            },
            Children = {
                textBox,
                button,
            },
        };
    }
}

I'm using .NET 3.5 and the WPF toolkit


It turns out you also need to override PrepareCellForEdit, CommitCellEdit and CancelCellEdit

The base class assumes (not unreasonably) that the FrameworkElement passed in will be a TextBox


I think you have to set up the binding manually in the GenerateEditingElement(...) method.

Once you've grabbed the TextBox from the base class, set up its binding like this:

textBox.DataContext = dataItem;
textBox.SetBinding(TextBlock.TextProperty, Binding);

This works for me anyway.

Note, I'm not sure why this works, as reading the documentation for GenerateEditingCell implies to me that the TextBox that you grab from the base class should already have its bindings set up properly. However, the above approach is what they did in this blog post.

EDIT:

You don't actually need to set up the binding, it is done already (as it says in the docs). You do need to set up the DataContext though, as for some reason this isn't set up on the textBox returned from the base class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜