2016-12-17 4 views
3

私はこのコードWPF TextBoxの無効な依存プロパティの赤い枠線を表示する方法はありますか

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> 

私はテキストボックスで無効な値を入力したときに赤い枠を表示したい.. ValidateXX方法、作業正しくが、赤を持っていますテキストボックスの枠線に枠線が表示されません。

答えて

2

バインディングを更新するには、 'ValidatesOnExceptions = True'属性を追加します。

Updateへ:

<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"/> 
関連する問題