views:

847

answers:

2

What I want is simply that all my TextBoxes as by default set their cursor at the end of the text so I want in pseudocode:

if (TextChanged) textbox.SelectionStart = textbox.Text.Length;

Because I want that all textboxes in my application are affected I want to use a style for that. This one won't work (for obvious reasons) but you get the idea:

<Style TargetType="{x:Type TextBox}">
  <Style.Triggers>
    <EventTrigger RoutedEvent="TextChanged">
      <EventTrigger.Actions>
        <Setter Property="SelectionStart" Value="{Binding Text.Length}"/>
      </EventTrigger.Actions>
    </EventTrigger>
  </Style.Triggers>
</Style>

EDIT: One important thing is that the SelectionStart property should only be set if the Text property was assigned programmatically, not when the user edits the textbox.

+1  A: 

Are you sure you want this behavior for ALL textboxes in your app ? it will make it almost impossible (or at least very painful) for the user to edit text in the middle of the TextBox...

Anyway, there is a way to do what you want... Assuming your style is defined in a ResourceDictionary file. First, you need to create a code-behind file for the resource dictionary (for instance, Dictionary1.xaml.cs). Write the following code in this file :

using System.Windows.Controls;
using System.Windows;

namespace WpfApplication1
{
    partial class Dictionary1
    {
        void TextBox_TextChanged(object sender, RoutedEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            if (textBox != null)
                textBox.SelectionStart = textBox.Text.Length;
        }
    }
}

In the XAML, add the x:Class attribute to the ResourceDictionary element :

<ResourceDictionary x:Class="WpfApplication1.Dictionary1"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;

Define your style as follows :

<Style TargetType="{x:Type TextBox}">
    <EventSetter Event="TextChanged" Handler="TextBox_TextChanged" />
</Style>

The TextBox_TextChanged method will now handle the TextChanged event of all textboxes.

It should be possible to write the code inline in the XAML using the x:Code attribute, but I couldn't make it work...

Thomas Levesque
Oh damn..I didn't think of that. I really need the SelectionStart only to be set if text changes programatically, e.g. if Text property is assigned to but not due to user edit.
codymanix
+1  A: 

Create an attached behaviour. Attached behaviours are a way of hooking up arbitrary event handling in such a way that it can be applied via a Style.

itowlson