开发者

Select all Silverlight DataGrid cell text on cell entry

开发者 https://www.devze.com 2023-03-11 09:46 出处:网络
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开发者_如何

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

精彩评论

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

关注公众号