2010-03-15 50 views
1

我正在使用IDataErrorInfo驗證WPF中的表單中的數據。我的演示者已經實施了驗證。將驗證錯誤傳遞給WPF中的UI元素?

實際驗證正在發生,但應該更新UI並設置樣式的XAML沒有發生。

這就是:

<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)[0].ErrorContent}"/> 
        <Setter Property="Background" Value="Red"/> 
       </Trigger> 
     </Style.Triggers> 
    </Style> 

的問題是,我結合Validation.Errors不包含任何數據。如何從Presenter類獲取這些數據並將其傳遞給此XAML以更新UI元素?

編輯:

文本框:

<TextBox Style="{StaticResource textBoxInError}" Name="txtAge" Height="23" Grid.Row="3" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Width="150"> 
      <TextBox.Text> 
       <Binding Path="StrAge" Mode="TwoWay" 
         ValidatesOnDataErrors="True" 
         UpdateSourceTrigger="PropertyChanged"/> 
      </TextBox.Text> 

驗證的發生,但數據無效時沒有發生要應用的風格。

+0

嘗試放置明確的s直接在樣式,而不是在觸發器部分,看看是否所有的樣式應用...也許文本框樣式被重寫在視覺樹的其他地方? – kiwipom 2010-03-16 01:18:42

回答

2

你看了輸出窗口爲您的形式被綁定?通過在輸出發生時檢查輸出,可以發現大量的驗證問題。

一個快速的注意,以及:

使用

Path=(Validation.Errors).CurrentItem.ErrorContent

而不是

Path=(Validation.Errors)[0].ErrorContent 

它會爲你節省一些進一步結合excecption當一個有效的值提供給控制

+0

你可以在這裏找到進一步的探索: http://demandingdev.blogspot.com/2010/11/wpf-validationtemplate.html – 2010-11-02 16:51:05

1

我注意到你的Style沒有完全完成。

樣式需要一個控制模板,該模板定義一個「Validation.ErrorTemplate」,以便在發生驗證錯誤時使其工作。嘗試進行以下更改以瞭解它是如何發生的。

Paul Stovell在WPF驗證here上有一篇很好的文章,它將涵蓋您需要的大部分內容。我還寫了一篇文章here以簡化您可能也喜歡的驗證。

<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)[0].ErrorContent}"/> 
      <Setter Property="Background" Value="Red"/> 
     </Trigger> 
    </Style.Triggers> 
</Style> 

<Style x:Key="textBoxInError" TargetType="{x:Type TextBox}"> 
    <Setter Property="Validation.ErrorTemplate"> 
     <Setter.Value> 
      <ControlTemplate> 
       <Border BorderBrush="Red" BorderThickness="1"> 
        <AdornedElementPlaceholder /> 
       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
    <Style.Triggers> 
     <Trigger Property="Validation.HasError" Value="true"> 
      <Setter Property="ToolTip" 
       Value="{Binding RelativeSource={RelativeSource Self}, 
         Path=(Validation.Errors)[0].ErrorContent}"/> 
     </Trigger> 
    </Style.Triggers> 
</Style> 
+0

您仍然遇到與錯誤內容路徑相同的問題,但問題更多的是如何處理數組的錯誤,以及如何在UI和綁定的對象之間進行通信。 – 2013-05-14 22:58:41