Change property from event trigger

I just want all my TextBoxes to set their cursor at the end of the text by default, so I want in pseudocode:

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

      

Since I want all text boxes in my application to be affected, I want to use a style for that. This one won't work (understandably), 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: The important thing is that the SelectionStart property should only be set if the Text property was assigned programmatically, not when the user is editing the textbox.

+2


source to share


2 answers


Are you sure you want to use this behavior for ALL text fields in your application? this will make it almost impossible (or at least very painful) for the user to be able to edit the 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 resource dictionary code file (eg 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 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 like this:

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

      

The method now TextBox_TextChanged

handles the event of TextChanged

all text fields.

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

+3


source


Create an attached behavior . Attached behavior is a way to wire up arbitrary event handling in such a way that it can be applied through a style.



+1


source







All Articles