Change Property from within event trigger

10,282

Solution 1

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">

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

Solution 2

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.

Share:
10,282
codymanix
Author by

codymanix

General interests Programming languages in general Especially .NET/C#/LINQ Database systems Low level stuff like C/Assembler Multimedia systems Game programming

Updated on June 04, 2022

Comments

  • codymanix
    codymanix almost 2 years

    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.