2017-07-04 27 views
0

看來WPF有一些默認開啓的驗證規則。當我將非數字文本輸入到綁定文本框並將其標記出來時,會在其周圍顯示一個讀取邊框。這裏發生了什麼?我已經將ValidatesOnExceptions設置爲false,驗證規則來自哪裏?我正在使用.Net框架的4.5.2版本。如何關閉WPF中的默認驗證?

這是我的XAML

<Window x:Class="WpfApplication2.MainWindow" 
      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:WpfApplication2" 
      mc:Ignorable="d" 
      Title="MainWindow" Height="159.206" Width="193.953"> 
     <Grid> 
      <TextBox x:Name="textBox" Height="23" HorizontalAlignment="Left" VerticalAlignment="Top" TextWrapping="Wrap" 
        Text="{Binding Foo, ValidatesOnExceptions=False, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" 
        Width="91" Margin="10,10,0,0"/> 
      <TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="23" Margin="10,48,0,0" 
        TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="91"/> 
     </Grid> 
</Window> 

這裏是背後

namespace WpfApplication2 
{ 
    public partial class MainWindow : Window 
    { 
     public int Foo { get; set; } = 42; 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 
    } 
} 

回答

1

的代碼,你可以從未設置int屬性爲別的不是一個有效int值。

無法關閉編程語言的「驗證」或者說類型安全功能。

但是,如果您願意,您可以擺脫或自定義默認錯誤模板。只需將Validation.ErrorTemplate屬性設置爲註釋ControlTemplate

<TextBox x:Name="textBox" Height="23" HorizontalAlignment="Left" VerticalAlignment="Top" TextWrapping="Wrap" 
     Text="{Binding Foo, ValidatesOnExceptions=False, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" 
     Width="91" Margin="10,10,0,0"> 
    <Validation.ErrorTemplate> 
     <ControlTemplate /> 
    </Validation.ErrorTemplate> 
</TextBox> 
+0

非常感謝。如果有一個int,該怎麼辦?我想要空白文本映射到null,這似乎不工作默認情況下。我是否必須編寫自定義轉換器?可能是 – Shane

+0

。您需要將空字符串轉換爲空。 String.Empty不是一個有效的int?值。 – mm8