2013-08-25 100 views
9

我的目標是到內容標籤,物業給標籤的元素的樣式應用到,物業結合。但我的解決方案似乎不工作: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 
    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是制定者只是收集,他不知道控制,在那裏。爲此,通常使用DataTemplateControlTemplate

作爲替代方案,在這種情況下,我建議使用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