如果我理解正確的話,你要爲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