如何在WPF TextBox上显示无效Dependency属性的红色边框?

时间:2016-12-17 13:52:44

标签: wpf validation xaml dependency-properties

我有这段代码

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

这个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>

我喜欢在TextBox中输入无效值时显示红色边框。 ValidateXX方法,正常工作但红色边框不出现在TextBox边框中。

1 个答案:

答案 0 :(得分:3)

更新绑定以添加'ValidatesOnExceptions = True'属性。

更新至:

<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, ValidatesOnExceptions=True}" VerticalAlignment="Top" Width="120"/>