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>
test 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: 17: "Item []" ( "ValidationError" ) "(Validation.Errors)" ( "ReadOnlyObservableCollection`1" ). BindingExpression:. = (0) (1) [0].ErrorContent; DataItem = 'MainWindow' (Name= 'w'); "TextBlock" (Name= ''); target is 'Text' (type 'String') ArgumentOutOfRangeException: 'System.ArgumentOutOfRangeException: .
, , Validation.Errors , [0] .
( ), - , , . , IInputElement, FocusManager.FocusedElement .
user128300