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.
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 :
In the XAML, add the x:Class attribute to the ResourceDictionary element :
Define your style as follows :
The
TextBox_TextChangedmethod will now handle theTextChangedevent 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…