I have this code
using System.Windows;
namespace TestWpfApplication
{
public partial class Window5 : Window
{
public Window5()
{
InitializeComponent();
}
public int XX
{
get { return (int)GetValue(XXProperty); }
set { SetValue(XXProperty, value); }
}
public static readonly DependencyProperty XXProperty =
DependencyProperty.Register("XX", typeof(int), typeof(Window5), new PropertyMetadata(1),ValidateXX);
private static bool ValidateXX(object value)
{
int? d =value as int?;
var res= d != null && d > 0 && d < 20;
return res;
}
}
}
And this XAML
<Window x:Class="TestWpfApplication.Window5"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TestWpfApplication"
mc:Ignorable="d"
Title="Window5" Height="300" Width="300">
<Grid>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="22" Margin="120,68,0,0" TextWrapping="Wrap" Text="{Binding XX, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:Window5}}, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="22" Margin="96,122,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
</Grid>
I like to show red border when enter the invalid value in TextBox.. ValidateXX method, work properly but red Border does not appear in TextBox Border.
Update your binding to Add the 'ValidatesOnExceptions=True' attribute.
Update to :