tags:

views:

21

answers:

1

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 select 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.

+1  A: 

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>
Dave
Easier than I hoped. But would this distinguish between nmemonic selection and mouse selection?
Andrew Shepherd
I've tested this, and it works how I want it to. Mnemonic selection causes all text to be selected, and mouse selection causes the cursor to go where you clicked the mouse. I don't understand why.
Andrew Shepherd
By mnemonic selection, I assumed that you just meant tabbing through the GUI. The first time the textbox gets the focus that event will get fired and cause the event handler to get called. I actually didn't test the mouse part. :)
Dave