如何在进入单元格时选择文本
问题描述:
我有一个Grid
,当我走过它的单元格时,我进入单元格,但没有选择文本。这很烦人,因为当我需要改变一个值时,我首先需要使用Backspace键。如何在进入单元格时选择文本
进入单元格后我能做些什么选择了单元格的内容?
答
我会建议使用这种行为。下面我已经包括一个最小的实现,它提供我认为功能你正在寻找:
/// <summary>
/// <see cref="Behavior{T}"/> of <see cref="TextBox"/> for selecting all text when the text box is focused
/// </summary>
public class TextBoxSelectOnFocusBehavior : Behavior<TextBox>
{
private void AssociatedObject_GotFocus(object sender, RoutedEventArgs e)
{
TextBox textBox = (sender as TextBox);
if (textBox != null)
textBox.SelectAll();
}
/// <summary>
/// React to the behavior being attached to an object
/// </summary>
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.GotFocus += AssociatedObject_GotFocus;
}
/// <summary>
/// React to the behavior being detached from an object
/// </summary>
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.GotFocus -= AssociatedObject_GotFocus;
}
}
希望这有助于。
+1但是应该提及的是在Blend SDK中找到了'Behavior'。此外,还需要一个模板化的网格列,一个简单的文本列将无法使用该行为。 –
AnthonyWJones
嗯,我天真地看到Grid并想象一个Grid容器与DataGrid控件相反,但再次阅读时,他提到的单元格似乎暗示了后者。所以是的,将文本块和附加行为嵌入到DataGridTemplateColumn中将是一条可行的路。 我也建议使用WeakReference,如果这种行为是在DataGrid中使用的,显然,OnDetaching并不总是在应该时被调用。 – ibebbs
感谢ibebbs的回复。不幸的是我不能使用DataGridTemplateColumn(它是遗留代码),所以这个解决方案不适合我:/ – user278618