2012-05-19

Articles

TextBoxBehavior

 

Some text boxes in applications have the behavior that all the text will be selected if the box got the focus. This you can have with this behavior. You also can work with the selection out of bound text.

 

alt

Usage

<UserControl x:Class="DW.Interactivity.Demo.TextBoxBehaviorControl"
			 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
			 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
			 xmlns:Interactivity="http://schemas.my-libraries.de/wpf/interactivity">
	<StackPanel>
		<TextBox Text="All is selected on got focus"
				 Interactivity:TextBoxBehavior.SelectAllOnFocus="True" />

		<TextBox Text="This is a demo text"
				 Interactivity:TextBoxBehavior.SelectedText="{Binding SelectedText}" />
		
		<Button Content="Select "demo"" HorizontalAlignment="Right" Margin="2"
				Click="Button_Click" />
	</StackPanel>
</UserControl>
using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Windows.Controls;

namespace DW.Interactivity.Demo
{
	public partial class TextBoxBehaviorControl : UserControl, INotifyPropertyChanged
	{
		public TextBoxBehaviorControl()
		{
			InitializeComponent();
			DataContext = this;
		}

		public string SelectedText
		{
			get { return _selectedText; }
			set
			{
				_selectedText = value;
				NotifyPropertyChanged(() => SelectedText);
			}
		}
		private string _selectedText;

		#region NotifyPropertyChanged
		public event PropertyChangedEventHandler PropertyChanged;
		void NotifyPropertyChanged<T>(Expression<Func<T>> property)
		{
			PropertyChangedEventHandler handler = PropertyChanged;
			if (handler != null)
			{
				var memberExpression = property.Body as MemberExpression;
				handler(this, new PropertyChangedEventArgs(memberExpression.Member.Name));
			}
		}
		#endregion NotifyPropertyChanged

		private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			SelectedText = "demo";
		}
	}
}

 

 

Note

This control needs the DW.SharpTools.