2015-12-17 7 views
0

Я использую .NET Framework 4.5, и у меня есть следующая проблема.WPF Adorner не работает, если он добавлен в Window.Resources

Если добавить Validation ErrorTemplate, как это, мой Adorner будет работать и кончик шоу инструмент и красный круг рядом с моей TextBox просто отлично:

// THIS IS WORKING FINE BUT ONLY FOR txtAge TextBox 
<TextBox x:Name="txtAge" 
     Validation.Error="Validation_Error" 
     Text="{Binding UpdateSourceTrigger=LostFocus, Path=Age, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" 
     HorizontalAlignment="Left" MaxLength="3" Width="50"> 

    <Validation.ErrorTemplate> 
     <ControlTemplate> 
      <DockPanel LastChildFill="true"> 
       <Border Background="Red" DockPanel.Dock="right" Margin="5,0,0,0" Width="20" Height="20" CornerRadius="10" 
        ToolTip="{Binding ElementName=customAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"> 
        <TextBlock Text="!" VerticalAlignment="center" HorizontalAlignment="center" FontWeight="Bold" Foreground="white"/> 
       </Border> 
       <AdornedElementPlaceholder Name="customAdorner" VerticalAlignment="Center" > 
        <Border BorderBrush="red" BorderThickness="1" /> 
       </AdornedElementPlaceholder> 
      </DockPanel> 
     </ControlTemplate> 
    </Validation.ErrorTemplate> 
</TextBox> 

Таким образом, шаблон проверки выше, добавляют в пределах <TextBox> тегов для моего TextBox txtAge и поэтому применяется только к этому TextBox.

Однако, я хотел бы иметь стиль, который применяется ко всем текстовым полям, поэтому я добавляю Adorner внутри тегов <Window.Resources>. Но это не будет ни показать, ни ToolTip красный круг:

// I WANT TO MAKE IT APPLY TO ALL TEXTBOXES BUT THIS IS NOT WORKING 
<Window.Resources> 
    <Style TargetType="{x:Type Label}"> 
     <Setter Property="Margin" Value="5,0,5,0" /> 
     <Setter Property="HorizontalAlignment" Value="Right" /> 
    </Style> 
    <Style TargetType="{x:Type TextBox}"> 
     <Setter Property="VerticalAlignment" Value="Center" /> 
     <Setter Property="Margin" Value="0,2,40,2" /> 
     <Setter Property="Validation.ErrorTemplate"> 
      <Setter.Value> 
       <ControlTemplate> 
        <DockPanel LastChildFill="true"> 
         <Border Background="Red" DockPanel.Dock="right" Margin="5,0,0,0" Width="20" Height="20" CornerRadius="10" 
           ToolTip="{Binding ElementName=customAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"> 
          <TextBlock Text="!" VerticalAlignment="center" HorizontalAlignment="center" FontWeight="Bold" Foreground="white"/> 
         </Border> 
         <AdornedElementPlaceholder Name="customAdorner" VerticalAlignment="Center" > 
          <Border BorderBrush="red" BorderThickness="1" /> 
         </AdornedElementPlaceholder> 
        </DockPanel> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
</Window.Resources> 

Почему первый один рабочий и второй один не является? Я новичок в WPF.

+0

Вы пробовали создать отдельный ресурс для шаблона ошибки, например, controltemplate x: Key = "errorTemplate" и использовать его в стиле Textbox? Правильно ли применяются другие свойства TextBox, например. маржа? – SnowballTwo

+0

@SnowballTwo Как создать отдельный ресурс? Я новичок в этом. Thansk – pixel

+1

Просто поместите ControlTemplate в качестве дочернего элемента в свой Window.Resources узел и добавьте атрибут x: Key. Вы можете обратиться к шаблону, написав {StaticResource YourTemplateKey} – SnowballTwo

ответ

0

На основании ответа @SnowballTwo я понял это.

Переместить код в Windows.Resources раздел и добавить его х: Key, как показано ниже:

<ControlTemplate x:Key="ValidationTemplate"> 
    <DockPanel LastChildFill="true"> 
     <Border Background="Red" DockPanel.Dock="right" 
          Margin="5,0,0,0" Width="10" Height="10" CornerRadius="10" 
          ToolTip="{Binding ElementName=customAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"> 
      <TextBlock Text="!" VerticalAlignment="center" HorizontalAlignment="center" FontWeight="Bold" Foreground="white"/> 
     </Border> 
     <AdornedElementPlaceholder Name="customAdorner" VerticalAlignment="Center" > 
      <Border BorderBrush="red" BorderThickness="1" /> 
     </AdornedElementPlaceholder> 
    </DockPanel> 
</ControlTemplate> 

Тогда для каждого TextBox, добавьте следующую строку для ссылки на ControlTemplate

Validation.ErrorTemplate="{StaticResource ValidationTemplate}"