2013-08-25 4 views
9

Моей цели, чтобы связать содержания -свойства в этикетке к Tag -свойства из элементов стиля применяются к. Но мое решение не похоже на работу:WPF - RelativeSource в стиле


Мой стиль:

<Style 
    TargetType="TextBox" 
    x:Key="HintedTextBox"> 
    <Style.Resources> 
     <VisualBrush 
     AlignmentX="Left" 
     AlignmentY="Center" 
     Stretch="None" 
     x:Key="HintedTextBox_Hint"> 
     <VisualBrush.Visual> 
      <Label 
       Content="{Binding RelativeSource={RelativeSource Self}, Path=Tag}" 
       Foreground="LightGray" /> 
     </VisualBrush.Visual> 
     </VisualBrush> 
    </Style.Resources> 
    <!-- Triggers --> 
</Style> 

Мой TextBox:

<TextBox 
    Style="{StaticResource ResourceKey=HintedTextBox}" 
    x:Name="tbTest" /> 

ответ

7

Если я правильно понимаю, вы хотите, чтобы задать текст для VisualBrush , который будет отображаться в TextBox.

Вы можете сделать это следующим образом:

<TextBox Name="MyTextBox" Tag="MyNewValue" Width="100" Height="25"> 
    <TextBox.Background> 
     <VisualBrush AlignmentX="Left" AlignmentY="Center" Stretch="None"> 
      <VisualBrush.Visual> 
       <Label Content="{Binding RelativeSource={RelativeSource AncestorType=TextBox}, Path=Tag}" Foreground="LightGray" /> 
      </VisualBrush.Visual> 
     </VisualBrush> 
    </TextBox.Background> 
</TextBox> 

Для того, чтобы объяснить, почему ваш пример не заработал:

1. Как вы, наверное, понимаете, глядя на моем примере, RelativeSource должен быть не self, и в этом случае он укажет на себя (VisualBrush), а элемент с типом должен быть TextBox, расположенный выше в визуальном дереве.

2. Связывание с RelativeSource не работает ресурсов, потому что Resource не является частью визуального дерева или части шаблона.

3. В стилях эта конструкция не будет работать, потому что Style просто коллекция сеттеров, он не знает о контроле, есть. Для этой цели обычно используют DataTemplate или ControlTemplate.

В качестве альтернативы, в данном случае, я предлагаю использовать шаблон для TextBox, который будет зарегистрирован VisualBrush.

Ниже мой пример:

<Window.Resources>    
    <Style TargetType="{x:Type TextBox}"> 
     <Setter Property="SnapsToDevicePixels" Value="True" /> 
     <Setter Property="OverridesDefaultStyle" Value="True" /> 
     <Setter Property="KeyboardNavigation.TabNavigation" Value="None" /> 
     <Setter Property="FocusVisualStyle" Value="{x:Null}" /> 
     <Setter Property="MinWidth" Value="120" /> 
     <Setter Property="MinHeight" Value="20" /> 
     <Setter Property="AllowDrop" Value="true" /> 

     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="{x:Type TextBoxBase}"> 
        <Border Name="Border" CornerRadius="0" Padding="2" BorderThickness="1" BorderBrush="Black"> 
         <Border.Background> 
          <VisualBrush AlignmentX="Left" AlignmentY="Center" Stretch="None"> 
           <VisualBrush.Visual> 
            <Label Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Tag}" 
              Foreground="LightGray" /> 
           </VisualBrush.Visual> 
          </VisualBrush> 
         </Border.Background> 

         <ScrollViewer Margin="0" x:Name="PART_ContentHost" /> 
        </Border> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
</Window.Resources> 

<Grid> 
    <TextBox Name="MyTextBox" Tag="MyNewValue" Width="100" Height="25" />   
</Grid> 

Output

enter image description here