My target is to bind the Content-Property of the Label to the Tag-Property of the Elements the Style is applied to. But my solution doesn't seem to work:
My style:
<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>
My textbox:
<TextBox
Style="{StaticResource ResourceKey=HintedTextBox}"
x:Name="tbTest" />
If I understand correctly, you want to set the text for
VisualBrush
, that will be displayed in theTextBox
.You can do it like this:
In order to explain why your example not earned:
1.
As you probably understand, looking at my example,RelativeSource
must be not self, in which case it will point to itself (VisualBrush
), and the element with the type must be ofTextBox
, located higher in the visual tree.2.
Binding withRelativeSource
does not work in resources, because theResource
is not part of the visual tree, or part of the template.3.
In styles this construction will not work, because theStyle
is just the collection of setters, he does not know about control, are there. For this purpose, usually usingDataTemplate
orControlTemplate
.As an alternative, in this case, I suggest using a template for the
TextBox
, which will be registeredVisualBrush
.Below is my example:
Output