开发者

Select all Silverlight DataGrid cell text on cell entry

I have a DataGrid in SL4 with a simple DataGridTextColumn columns.

I've tried a number of different methods to select all the text in a DataGridCell as soon as the cell changes to an edit开发者_如何学运维able TextBox.

The code below was my last attempt.

Inspecting the TextBox in debug shows that the SelectedText property is equal to the Text property. So the problem isn't the TextBox. It seems something is deselecting the text later on.

public void PreparingCellForEdit(DataGridPreparingCellForEditEventArgs e)
    {
        var textBox = e.EditingElement as TextBox;
        if (textBox != null && !string.IsNullOrEmpty(textBox.Text))
        {
            textBox.GotFocus += (s, e2) =>
                {
                    {
                        textBox.SelectAll();
                    }
                };
        }
    }

Any ideas how to keep the text selected and display the TextBox with the selected text to the user?

P.S. I am using Cliburn.Micro to attach the PreparingCellForEdit event.


What works better for me is the following:

public void PreparingCellForEdit(DataGridPreparingCellForEditEventArgs e)
{
    var textBox = e.EditingElement as TextBox;
    if (textBox != null)
    {
        textBox.Dispatcher.BeginInvoke(() => textBox.SelectAll());
    }
}


Somewhat of solution is to force focus to the TextBox after attaching to the GotFocus event.

Like this:

    public void PreparingCellForEdit(DataGridPreparingCellForEditEventArgs e)
    {
        var textBox = e.EditingElement as TextBox;
        if (textBox != null)
        {
            textBox.GotFocus += (s, e2) => textBox.SelectAll();
            textBox.Focus();
        }
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜