IMHO TextBox 컨트롤에 StyleSelector을 사용할 수 없습니다. 그건 내 잘못 이었어. 대신 스위치 TextBox 스타일에 간단한 변환기를 사용할 수 있습니다.
여기 샘플 코드 :
모델 :
public class User : ModelBase
{
private string _login;
[Required(ErrorMessage = "Login can not be empty")]
[MaxLength(20, ErrorMessage = "Login max lenght is 20")]
public string Login
{
get
{
return _login;
}
set
{
_login = value;
OnPropertyChanged("Login");
}
}
}
는 App.xaml에서 사용자 지정 오류 템플릿 텍스트 상자 스타일을 만듭니다.
App.xaml
<Application.Resources>
<Style x:Key="AsteriskErrorStyle"
TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<StackPanel Orientation="Horizontal">
<AdornedElementPlaceholder x:Name="AdornedElementPlaceholder" />
<TextBlock Foreground="Red"
Margin="10,0,0,0"
VerticalAlignment="Top"
FontSize="20"
Text="*"
ToolTip="{Binding ElementName=AdornedElementPlaceholder, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
</TextBlock>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="RedBorderErrorStyle"
TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<Border BorderThickness="1.5"
BorderBrush="Red">
<AdornedElementPlaceholder x:Name="AdornedElementPlaceholder" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
변환기 :
public class TextBoxStyleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string textBoxTex = value.ToString();
var asteriskErrorStyle = Application.Current.FindResource("AsteriskErrorStyle") as Style;
var redBorderErrorStyle = Application.Current.FindResource("RedBorderErrorStyle") as Style;
if (string.IsNullOrEmpty(textBoxTex))
{
return asteriskErrorStyle;
}
else
{
return redBorderErrorStyle;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
용도 :
<Window.Resources>
<styleSelector:TextBoxStyleConverter x:Key="TextBoxStyleConverter"/>
</Window.Resources>
<TextBox Grid.Column="1"
Grid.Row="0"
Margin="5,5,80,5"
Style="{Binding RelativeSource={RelativeSource Self}, Path=Text,Converter={StaticResource TextBoxStyleConverter}}"
Text="{Binding Path=User.Login, ValidatesOnNotifyDataErrors=True}" >
샘플 프로젝트를 다운로드 할 수 있습니다 here.
출처
2014-02-05 21:34:09
Jan
코드 예제가 좋을 것입니다. –