Jeśli dobrze rozumiem, chcesz ustawić tekst VisualBrush
, które będą wyświetlane w TextBox
.
Można to zrobić tak:
<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>
Aby wyjaśnić, dlaczego Twój przykład nie zdobył:
1.
Jak zapewne zrozumieć, patrząc na moim przykładzie, RelativeSource
musi być nie self, w takim przypadku będzie wskazywać na siebie (VisualBrush
), a element z typem musi być z TextBox
, znajdujący się wyżej w drzewie wizualnym.
2.
Oprawa z RelativeSource
nie działa w zasoby, ponieważ Resource
nie jest częścią drzewa wizualnej, lub częścią szablonu.
3.
W stylach konstrukcja ta nie będzie działać, ponieważ Style
jest po prostu zbiorem ustawiaczy, że nie wie o kontroli, są tam. W tym celu zwykle używa się DataTemplate
lub.
Alternatywnie, w tym przypadku sugeruję użycie szablonu dla TextBox
, który zostanie zarejestrowany pod numerem VisualBrush
.
Poniżej jest mój przykład:
<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
