2014-02-05 2 views
0

TextBoxBase를 기반으로 컨트롤의 기본 Validation.ErrorTemplate을 수정했습니다. 입력란에 포커스가있을 때 오류를 표시하는 툴팁 및 라벨이 표시되도록하려면컨트롤 상태를 기반으로 Validation.ErrorTemplate을 설정하십시오.

컨트롤에 텍스트가 있지만 입력이 필요하면 컨트롤의 왼쪽에 빨간색 테두리를 별표 *로 바꾸려면 기본 빨간색 테두리를 제거하고 싶습니다.

많은 필수 입력란이있는 경우 사용하면 무서운 빨간색 상자가 가득 찬 양식이 사용됩니다. 빨간색 테두리는 223과 같은 유효하지 않은 값을 입력 한 경우에만 표시되어야합니다.

그래서 템플릿이나 템플릿을 트리거 기반으로 전환하려고합니다.

답변

0

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.

+0

코드 예제가 좋을 것입니다. –

0

Binding.ValidatesOnExceptionsBinding.ValidatesOnDataErrors 속성을 False으로 설정하여 기본 빨간색 Border이 표시되지 않도록 할 수 있습니다. 이미 발견 한 것 같이 당신은 Validation.ErrorTemplate 속성을 사용하여 별표를 적용 할 수 있습니다

<ControlTemplate x:Key="RedAsteriskValidationTemplate"> 
    <StackPanel Orientation="Horizontal"> 
     <TextBlock Text="*" Foreground="Red" FontWeight="Bold" Margin="0,0,5,0" /> 
     <AdornedElementPlaceholder /> 
    </StackPanel> 
</ControlTemplate> 

당신은 MSDN에 Validation.ErrorTemplate property 페이지에 Trigger을 사용하는 것을 포함하여 더 많은 예제를 찾을 수 있습니다.

+0

물론 그럴 수 있지만 유효성 검사 규칙을 사용하여 UI를 실행하고 싶습니다. 그리고 같은 속성에 대해 빈 규칙과 범위 규칙을 둘 수 있습니다. 비어 있지 않으면 별표가 표시되고 범위 규칙에는 테두리가 표시되고 오류 메시지와 함께 작은 팝업이 표시됩니다. –

관련 문제