TextBox: set text, select all, clear, prepend, insert, append, cut, paste, undo


   
  
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPF" Height="300" Width="300">
    <StackPanel>
        <TextBox AcceptsReturn="True" Height="100" IsReadOnly="True" 
                 Name="textBox1" TextAlignment="Left" TextWrapping="Wrap" 
                 VerticalScrollBarVisibility="Auto">
            Default starting text.
        </TextBox>
        <WrapPanel Margin="10">
            <Button Margin="5" Name="textButton" Width="75" Click="TextButton_Click">Set Text</Button>
            <Button Margin="5" Name="selectAllButton" Width="75" Click="SelectAllButton_Click">Select All</Button>
            <Button Margin="5" Name="clearButton" Width="75" Click="ClearButton_Click">Clear</Button>
            <Button Margin="5" Name="prependButton" Width="75" Click="PrependButton_Click">Prepend</Button>
            <Button Margin="5" Name="insertButton" Width="75" Click="InsertButton_Click">Insert</Button>
            <Button Margin="5" Name="appendButton" Width="75" Click="AppendButton_Click">Append</Button>
            <Button Margin="5" Name="cutButton" Width="75" Click="CutButton_Click">Cut</Button>
            <Button Margin="5" Name="pasteButton" Width="75" Click="PasteButton_Click">Paste</Button>
            <Button Margin="5" Name="undoButton" Width="75" Click="UndoButton_Click">Undo</Button>
        </WrapPanel>
    </StackPanel>
</Window>
//File:Window.xaml.cs
using System.Windows;
using System.Windows.Controls;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
        private void AppendButton_Click(object sender, RoutedEventArgs e)
        {
            textBox1.AppendText("text");
        }
        private void ClearButton_Click(object sender, RoutedEventArgs e)
        {
            textBox1.Clear();
        }
        private void CutButton_Click(object sender, RoutedEventArgs e)
        {
            if (textBox1.SelectionLength == 0)
            {
                MessageBox.Show("Select text to cut first.", Title);
            }
            else
            {
                MessageBox.Show("Cut: " + textBox1.SelectedText, Title);
                textBox1.Cut();
            }
        }

        private void InsertButton_Click(object sender, RoutedEventArgs e)
        {
            textBox1.Text = textBox1.Text.Insert(textBox1.CaretIndex, "text");
        }

        private void PasteButton_Click(object sender, RoutedEventArgs e)
        {
            textBox1.Paste();
        }

        private void PrependButton_Click(object sender, RoutedEventArgs e)
        {
            textBox1.Text = textBox1.Text.Insert(0, "Prepend");
        }
        private void SelectAllButton_Click(object sender, RoutedEventArgs e)
        {
            textBox1.SelectAll();
            textBox1.Focus();
        }

        private void TextButton_Click(object sender, RoutedEventArgs e)
        {
            textBox1.Text = "new value";
        }

        private void UndoButton_Click(object sender, RoutedEventArgs e)
        {
            textBox1.Undo();
        }
    }
}

   
    
     


Handler for the PreviewKeyDown event on the TextBox


   
  

<Window x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Window1" Height="300" Width="300">
  <Grid>
    <StackPanel>
      <TextBox x:Name="uv" PreviewKeyDown="TextBox_PreviewKeyDown" />

    </StackPanel>
  </Grid>
</Window>


//File:Window1.xaml.cs
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            DataContext = this;
        }

        //
        private void TextBox_PreviewKeyDown(object sender, RoutedEventArgs e)
        {
            TextBox textBox = sender as TextBox;

            if (textBox != null)
            {
                textBox.Foreground = Brushes.Firebrick;
            }
        }
    }
}

   
    
     


Listen to TextBox text changed event


   
  

<Window x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title=" " Height="300" Width="300" Loaded="Window1_Loaded">
  <Grid>
    <Viewbox>
      <TextBox x:Name="tbxEditMe" Text="Edit Me..." />
    </Viewbox>      
  </Grid>
</Window>


//File:Window.xaml.cs
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            DependencyPropertyDescriptor descriptor = DependencyPropertyDescriptor.FromProperty(TextBox.TextProperty, typeof(TextBox));
            descriptor.AddValueChanged(tbxEditMe, tbxEditMe_TextChanged);
            
        }

        private void tbxEditMe_TextChanged(object sender, EventArgs e)
        {
            MessageBox.Show("", "changed");
        }
    }
}

   
    
     


Assign your own class to DataContent and bind to TextBox


   
  

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="BindingWithFallback" Height="300" Width="300">
    <StackPanel>
      <TextBox Text="{Binding Path=FastProperty, Mode=OneWay}" IsReadOnly="True" />
    </StackPanel>
</Window>

//File:Window.xaml.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;


namespace WpfApplication1{

  class MyClass {
    public string FastProperty { get { return "AAA"; } }
  }

  public partial class Window1 : System.Windows.Window {

    public Window1() {
      InitializeComponent();
      DataContext = new MyClass();
    }

  }
}

   
    
     


TextBox MouseLeftButtonDown action and PreviewMouseLeftButtonDown action


   
  

<Window x:Class="TunnelingBubbling.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="TunnelingBubbling">
  
    <Grid MouseLeftButtonDown="MouseDownGrid"
          PreviewMouseLeftButtonDown="PreviewMouseDownGrid"
      Width="300" Height="300">

    <Button PreviewMouseLeftButtonDown="PreviewMouseDownButton"
      MouseLeftButtonDown="MouseDownButton"
      Click="MyClickEvent"
      Name="btnGo">

      <TextBox MouseLeftButtonDown="MouseLeftButtonDown"
        PreviewMouseLeftButtonDown="PreviewMouseLeftButtonDown"
        Width="200" Height="30" Name="textBox1">
      </TextBox>
    </Button>
  </Grid>  
</Window>
//File:Window.xaml.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Diagnostics;

namespace TunnelingBubbling
{
    public partial class Window1 : System.Windows.Window
    {

        public Window1()
        {
            InitializeComponent();
        }

        private void PreviewMouseDownGrid(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("PreviewMouseDownGrid");
        }

        private void PreviewMouseDownButton(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("PreviewMouseDownButton");
        }

        private void PreviewMouseLeftButtonDown(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("PreviewMouseLeftButtonDown");
        }

        private void MyClickEvent(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("MyClickEvent");
        }

        private void MouseLeftButtonDown(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("MouseLeftButtonDown");
        }

        private void MouseDownButton(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("MouseDownButton");
        }

        private void MouseDownGrid(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("MouseDownGrid");
        }

    }
}

   
    
     


TextBox with default ErrorTemplate


   
  

<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:c="clr-namespace:WpfApplication1"
  x:Class="WpfApplication1.Window1"
  Title="Binding Validation Sample"
  SizeToContent="WidthAndHeight"
  ResizeMode="NoResize">
    <Window.Resources>
        <c:MyDataSource x:Key="ods"/>

    </Window.Resources>
    <StackPanel>
        <TextBox Name="textBox2" Width="50" FontSize="15">
            <TextBox.Text>
                <Binding Path="Age2" Source="{StaticResource ods}" UpdateSourceTrigger="PropertyChanged" >
                    <Binding.ValidationRules>
                        <c:AgeRangeRule Min="21" Max="30"/>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>

    </StackPanel>
</Window>

//File:Window.xaml.cs
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Globalization;
using System.Collections.ObjectModel;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
    }
    public class AgeRangeRule : ValidationRule
    {
        private int _min;
        private int _max;

        public AgeRangeRule()
        {
        }

        public int Min
        {
            get { return _min; }
            set { _min = value; }
        }

        public int Max
        {
            get { return _max; }
            set { _max = value; }
        }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            int age = 0;

            try
            {
                if (((string)value).Length > 0)
                    age = Int32.Parse((String)value);
            }
            catch (Exception e)
            {
                return new ValidationResult(false, "Illegal characters or " + e.Message);
            }

            if ((age < Min) || (age > Max))
            {
                return new ValidationResult(false,
                  "Please enter an age in the range: " + Min + " - " + Max + ".");
            }
            else
            {
                return new ValidationResult(true, null);
            }
        }
    }

    public class MyDataSource
    {
        private int _age;
        private int _age2;
        private int _age3;

        public MyDataSource()
        {
            Age = 0;
            Age2 = 0;
        }

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }
        public int Age2
        {
            get { return _age2; }
            set { _age2 = value; }
        }

        public int Age3
        {
            get { return _age3; }
            set { _age3 = value; }
        }
    }
}

   
    
     


TextBox with UpdateSourceExceptionFilter handler


   
  

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:c="clr-namespace:WpfApplication1"
  x:Class="WpfApplication1.Window1">
    <Window.Resources>
        <c:MyDataSource x:Key="ods"/>
        <ControlTemplate x:Key="validationTemplate">
            <DockPanel>
                <TextBlock Foreground="Red" FontSize="20">!</TextBlock>
                <AdornedElementPlaceholder/>
            </DockPanel>
        </ControlTemplate>
        <Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip"
              Value="{Binding RelativeSource={x:Static RelativeSource.Self},Path=(Validation.Errors)&#91;0&#93;.ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <StackPanel>
        <TextBox Name="textBox3" Width="50" FontSize="15"
             Validation.ErrorTemplate="{StaticResource validationTemplate}"
             Style="{StaticResource textBoxInError}">
            <TextBox.Text>
                <Binding Path="Age3" Source="{StaticResource ods}" UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <ExceptionValidationRule/>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>

        <CheckBox Name="cb" Checked="UseCustomHandler" Unchecked="DisableCustomHandler">Enable Custom Handler (see ToolTip)</CheckBox>
    </StackPanel>
</Window>

//File:Window.xaml.cs
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Globalization;
using System.Collections.ObjectModel;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        void UseCustomHandler(object sender, RoutedEventArgs e)
        {
            BindingExpression myBindingExpression = textBox3.GetBindingExpression(TextBox.TextProperty);
            Binding myBinding = myBindingExpression.ParentBinding;
            myBinding.UpdateSourceExceptionFilter = new UpdateSourceExceptionFilterCallback(ReturnExceptionHandler);
            myBindingExpression.UpdateSource();
        }

        void DisableCustomHandler(object sender, RoutedEventArgs e)
        {
            Binding myBinding = BindingOperations.GetBinding(textBox3, TextBox.TextProperty);
            myBinding.UpdateSourceExceptionFilter -= new UpdateSourceExceptionFilterCallback(ReturnExceptionHandler);
            BindingOperations.GetBindingExpression(textBox3, TextBox.TextProperty).UpdateSource();
        }

        object ReturnExceptionHandler(object bindingExpression, Exception exception)
        {
            return "This is from the UpdateSourceExceptionFilterCallBack.";
        }
    }
    public class AgeRangeRule : ValidationRule
    {
        private int _min;
        private int _max;

        public AgeRangeRule()
        {
        }

        public int Min
        {
            get { return _min; }
            set { _min = value; }
        }

        public int Max
        {
            get { return _max; }
            set { _max = value; }
        }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            int age = 0;

            try
            {
                if (((string)value).Length > 0)
                    age = Int32.Parse((String)value);
            }
            catch (Exception e)
            {
                return new ValidationResult(false, "Illegal characters or " + e.Message);
            }

            if ((age < Min) || (age > Max))
            {
                return new ValidationResult(false,
                  "Please enter an age in the range: " + Min + " - " + Max + ".");
            }
            else
            {
                return new ValidationResult(true, null);
            }
        }
    }

    public class MyDataSource
    {
        private int _age;
        private int _age2;
        private int _age3;

        public MyDataSource()
        {
            Age = 0;
            Age2 = 0;
        }

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }
        public int Age2
        {
            get { return _age2; }
            set { _age2 = value; }
        }

        public int Age3
        {
            get { return _age3; }
            set { _age3 = value; }
        }
    }
}