Overriding DataGridTextColumn

℡╲_俬逩灬. 提交于 2020-01-14 12:59:27

问题


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 DataGridFileColumn : 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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/7243235/overriding-datagridtextcolumn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!