2012-05-12 88 views
3

我想在屏幕的一個位置顯示錯誤(IDataErrorInfo.Errors),而不是顯示附近的錯誤內容..所以爲此,我已經將textBlock放置在窗體的末尾。我可以獲取綁定的當前焦點元素(Validation.Errors)[0] .ErrorContent。在WPF中獲取焦點元素throgh XAML

這應該在XAML中完成,而不是在代碼後面。

當焦點改變,那麼該元素的錯誤內容會顯示在屏幕的該TextBlock中放置底部..

感謝&問候 Dineshbabu Sengottian

回答

3

您可以訪問使用FocusManager.FocusedElement聚焦元素。下面是與XAML工作純粹,無一例任何代碼隱藏(當然除了必要的代碼隱藏,以提供IDataErrorInfo錯誤用於測試的):

<Window x:Class="ValidationTest.MainWindow" 
     x:Name="w" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 

    <StackPanel> 
     <TextBox x:Name="txt1" Text="{Binding Path=Value1, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, Mode=TwoWay}"/> 
     <TextBox x:Name="txt2" Text="{Binding Path=Value2, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, Mode=TwoWay}"/> 
     <TextBlock Foreground="Red" Text="{Binding 
         RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, 
         Path=(FocusManager.FocusedElement).(Validation.Errors)[0].ErrorContent}"/> 
    </StackPanel> 
</Window> 

測試類MainWindow有以下代碼:

namespace ValidationTest 
{ 
    public partial class MainWindow : Window, IDataErrorInfo 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 

      DataContext = this; 

      Value1 = "a"; 
      Value2 = "b"; 
     } 

     public string Value1 { get; set; } 
     public string Value2 { get; set; } 

     #region IDataErrorInfo Members 

     public string Error 
     { 
      get { return ""; } 
     } 

     public string this[string name] 
     { 
      get 
      { 
       if (name == "Value1" && Value1 == "x") 
       { 
        return "Value 1 must not be x"; 
       } 
       else if (name == "Value2" && Value2 == "y") 
       { 
        return "Value 2 must not be y"; 
       } 
       return ""; 
      } 
     } 

     #endregion 
    } 
} 

對於測試,如果在第一個文本框中放置「x」或者在第二個文本框中放入「y」,則會出現驗證錯誤。

當前焦點文本框的錯誤消息出現在TextBlock中兩個文本框的下方。

請注意,此解決方案有一個缺點。如果您在調試器下運行該示例,你會看到那些綁定錯誤:發生

System.Windows.Data Error: 17 : Cannot get 'Item[]' value (type 'ValidationError') from '(Validation.Errors)' (type 'ReadOnlyObservableCollection`1'). BindingExpression:Path=(0).(1)[0].ErrorContent; DataItem='MainWindow' (Name='w'); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String') ArgumentOutOfRangeException:'System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.

這些調試錯誤消息當前焦點元素有當沒有驗證錯誤,因爲Validation.Errors數組是空的,因此[0]是非法的。

您可以選擇忽略這些錯誤消息(示例仍然正常運行),或者您仍然需要一些代碼隱藏,例如,將從FocusManager.FocusedElement返回的IInputElement轉換爲字符串的轉換器。

+0

你好我有TextBox的ControlTemplate所以只適用於TextBox它不工作..是我在TextBox的ControlTemplate中缺少的任何東西..否則它是工作正常的PasswordBox ..謝謝.. – dinesh