당신은 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의 두 텍스트 상자 아래에 나타납니다.
이 솔루션에는 한 가지 단점이 있습니다. 현재 포커스 요소가없는 유효성 검사 오류가있을 때 Validation.Errors
배열이 비어 있기 때문에,
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.
이 디버그 오류 메시지가 발생, 따라서 [0]
불법 : 당신이 디버거에서 샘플을 실행하면, 당신은 그 바인딩 오류가 표시됩니다 .
오류 메시지를 무시하도록 선택할 수 있으며 (샘플은 여전히 정상적으로 실행 됨) 그럼에도 불구하고 코드 숨김이 필요합니다 (예 : IInputElement
을 FocusManager.FocusedElement
에서 문자열로 변환하는 변환기입니다.
안녕하세요, TextBox 용 ControlTemplate이 있습니다. TextBox 전용입니다. 작동하지 않습니다. 그게 내가 TextBox의 ControlTemplate에서 누락 된 것입니까? 그렇지 않으면 PasswordBox에서 잘 작동합니다. 감사 ... – dinesh