WPF mnemonic selection doesn't behave like WinForms mnemonic selection
I'm maintaining a hybrid application, containing both WinForms and WPF technologies. Ideally, the look-and-feel should be identical between the WPF controls and the WinForms controls.
Here's the difference: in WinForms, if you select a text box with a mnemonic key, the entire contents of the text box is automatically selected. This is good behavior: if you want to replace the text, you simply press the menmonic keys and start typing.
In WPF, if you se开发者_开发技巧lect a text box with a mnemonic key, the cursor appears at the BEGINNING of the text. Why would anyone want the cursor to be at the beginning? How often do people want to PREPEND to the text?
Does anyone know if there is an easy way to change the behavior of a WPF text box, so that activating the text box with a mnemonic selects the whole text? However, activating the text box with the mouse button should place the cursor wherever you clicked the mouse.
I don't know if this is "easy" or not... create an event handler that will select all of the text in a TextBox:
public void OnGotKeyboardFocus( Object sender, EventArgs e)
{
TextBox text = sender as TextBox;
if( text == null)
return;
text.SelectAll();
}
And then create a style that globally applies to all TextBoxes. I have it in my Windows.Resources, but you could put it in App.Resources instead, I think.
<Window x:Class="TextBoxSelectAll.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}">
<EventSetter Event="GotKeyboardFocus" Handler="OnGotKeyboardFocus" />
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBox Grid.Row="0"></TextBox>
<TextBox Grid.Row="1"></TextBox>
</Grid>
</Window>
精彩评论