TextBox uses the ExceptionValidationRule and 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; }
        }
    }
}

   
    
     


TextBox with custom ErrorTemplate and ToolTip


   
  

<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"/>
        <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="textBox1" Width="50" Validation.ErrorTemplate="{StaticResource validationTemplate}"
             Style="{StaticResource textBoxInError}">
            <TextBox.Text>
                <Binding Path="Age" 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();
        }

   
        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; }
        }
    }
}

   
    
     


TextBox focus listener


   
  
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:custom="clr-namespace:WpfApplication1"
    Title="Keyboard Sample" Height="250" Width="300">
    <StackPanel>
        <Label Name="lblNumberOfTargetHits" HorizontalAlignment="Center"/>
        <TextBox Name="txtTargetKey" GotKeyboardFocus="TextBoxGotKeyboardFocus" LostKeyboardFocus="TextBoxLostKeyboardFocus">A</TextBox>
        <TextBox TextWrapping="Wrap" GotKeyboardFocus="TextBoxGotKeyboardFocus" LostKeyboardFocus="TextBoxLostKeyboardFocus" KeyDown="SourceTextKeyDown"/>
    </StackPanel>

</Window>


//File:Window.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Annotations;
using System.Windows.Input;
namespace WpfApplication1
{
    public partial class Window1 : Window
    {

        public Window1()
        {
            InitializeComponent();
        }

        private void TextBoxGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            TextBox source = e.Source as TextBox;
            if (source != null)
            {
                source.Background = Brushes.LightBlue;
                source.Clear();
            }
        }
        private void TextBoxLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            TextBox source = e.Source as TextBox;

            if (source != null)
            {
                source.Background = Brushes.White;
            }
        }
        private void SourceTextKeyDown(object sender, KeyEventArgs e)
        {
            KeyConverter converter = new KeyConverter();
            Key target = Key.None;

            if (txtTargetKey.Text.Length == 1)
            {
                target = (Key)converter.ConvertFromString(txtTargetKey.Text);
            }
        }
    }
}

   
    
     


Bind TextBlock to TextBox


   
     
<Window x:Class="FontViewer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Teach Yourself WPF: Font Viewer"
        Height="480"
        Width="640">
    <DockPanel Margin="8">

        <ListBox x:Name="FontList"
                 DockPanel.Dock="Left"
                 ItemsSource="{x:Static Fonts.SystemFontFamilies}"
                 Width="160" />
        <TextBox x:Name="SampleText"
                 DockPanel.Dock="Bottom"
                 MinLines="4"
                 Margin="8 0"
                 TextWrapping="Wrap">
            <TextBox.ToolTip>
                <TextBlock>
                    <Italic Foreground="Red">Instructions: </Italic> Type here to change the preview text.
                </TextBlock>
            </TextBox.ToolTip>
            The quick brown fox jumps over the lazy dog.
        </TextBox>
        <StackPanel Margin="8 0 8 8">
            <TextBlock Text="{Binding ElementName=SampleText, Path=Text}"
                       FontFamily="{Binding ElementName=FontList,Path=SelectedItem}"
                       FontSize="10"
                       TextWrapping="Wrap"
                       Margin="0 0 0 4" />
            <TextBlock Text="{Binding ElementName=SampleText, Path=Text}"
                       FontFamily="{Binding ElementName=FontList,Path=SelectedItem}"
                       FontSize="16"
                       TextWrapping="Wrap"
                       Margin="0 0 0 4" />
            <TextBlock Text="{Binding ElementName=SampleText, Path=Text}"
                       FontFamily="{Binding ElementName=FontList,Path=SelectedItem}"
                       FontSize="24"
                       TextWrapping="Wrap"
                       Margin="0 0 0 4" />
            <TextBlock Text="{Binding ElementName=SampleText, Path=Text}"
                       FontFamily="{Binding ElementName=FontList,Path=SelectedItem}"
                       FontSize="32"
                       TextWrapping="Wrap" />
        </StackPanel>
    </DockPanel>
</Window>

   
    
    
    
    
     


TextBox Style


   
    
<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="220" Width="300">
    <Window.Resources>
        <Style x:Key="BaseControlStyle" 
               TargetType="{x:Type Control}">
            <Setter Property="FontFamily" Value="Tahoma" />
            <Setter Property="FontSize" Value="24pt"/>
            <Setter Property="Margin" Value="4" />
        </Style>

        <Style TargetType="{x:Type Button}" 
               BasedOn="{StaticResource BaseControlStyle}">
            <Setter Property="FontWeight" Value="Bold" />
        </Style>

        <Style TargetType="{x:Type CheckBox}" 
               BasedOn="{StaticResource BaseControlStyle}">
        </Style>
        <Style TargetType="{x:Type TextBox}" 
               BasedOn="{StaticResource BaseControlStyle}">
        </Style>

    </Window.Resources>

    <Grid>
        <StackPanel>
            <CheckBox>CheckBox</CheckBox>
            <TextBox>TextBox</TextBox>
            <Button>Button</Button>
            <Button FontWeight="Light">Button with overridden style</Button>
            <TextBlock>TextBlock</TextBlock>
            <ComboBox>ComboBox</ComboBox>
        </StackPanel>
    </Grid>
</Window>

   
    
    
    
     


VerticalAlignment=Top HorizontalAlignment=Left


   
  

<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>
        <Button Height="23" Margin="12,12,0,0" Name="button1" VerticalAlignment="Top" 
                HorizontalAlignment="Left" Width="76" Click="button1_Click">Button</Button>
        <TextBlock
            FontSize="16"
            Name="textBlock1"
            VerticalAlignment="Center"
            HorizontalAlignment="Center"
            xml:space="preserve"><Bold>Goodbye</Bold> world, <Rectangle Width="20" Height="20" Fill="Blue"/> hello <Italic>Mars!</Italic></TextBlock>
    </Grid>
</Window>

//File:Window.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
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.Navigation;
using System.Windows.Shapes;

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

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Please don’t click this button again");
        }
    }
}

   
    
     


Use Run the mark underlink TextDecorations


   
  


<Window x:Class="ClassicControls.PopupTest"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="PopupTest" Height="300" Width="300">
    <Grid Margin="10">
      <TextBlock TextWrapping="Wrap">text 
         <Run TextDecorations="Underline" MouseEnter="run_MouseEnter">link</Run>
      </TextBlock>
      <Popup Name="popLink" StaysOpen="False" Placement="Mouse" MaxWidth="200" PopupAnimation="Slide" AllowsTransparency = "True">
        <Border BorderBrush="Beige" BorderThickness="2" Background="White">
          <TextBlock Margin="10"  TextWrapping="Wrap" >
            check out
            <Hyperlink NavigateUri="http://kutayzorlu.com/java2s/com" Click="lnk_Click">kutayzorlu.com/java2s/com</Hyperlink>
          </TextBlock>
        </Border>
      </Popup>
    </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 ClassicControls
{
    public partial class PopupTest : System.Windows.Window
    {

        public PopupTest()
        {
            InitializeComponent();
        }

        private void run_MouseEnter(object sender, MouseEventArgs e)
        {
            popLink.IsOpen = true;
        }
        private void lnk_Click(object sender, RoutedEventArgs e)
        {
            Process.Start(((Hyperlink)sender).NavigateUri.ToString());
        }
    }
}