我有一个小问题,我似乎无法解决。 我有一个文本框,我要在其中添加“搜索提示”
我正在使用这个 XAML 代码段
<TextBox x:Name="txtboxSearch" Height="22" Margin="3,35,111,0" TextWrapping="Wrap" VerticalAlignment="Top" BorderThickness="1" MaxLines="1" MaxLength="256" Grid.Column="2" BorderBrush="#FF828790">
<TextBox.Style>
<Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
<VisualBrush.Visual>
<TextBox Text="Search" Foreground="LightGray" FontStyle="Italic" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Style.Triggers>
<Trigger Property="Text" Value="{x:Static sys:String.Empty}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter Property="Background" Value="White" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
因为窗口的背景不是白色,所以我得到的结果如图所示。我尝试以多种不同的方式绑定(bind)宽度,但似乎没有任何效果,您能提出建议吗?
我希望它看起来像这样
谢谢!
最佳答案
执行此操作的方法是将 CueBannerBrush(您的 VisualBrush)中的 TextBox 的宽度绑定(bind)到主 TextBox 父级 (txtboxSearch)。
但是,这仅在将 CueBannerBrush 定义放入控件或窗口资源而不是 TextBox.Style 资源中时有效:
<Window.Resources>
<VisualBrush x:Key="CueBannerBrush" TileMode="Tile" Stretch="None" AlignmentX="Left" AlignmentY="Center" >
<VisualBrush.Visual>
<TextBox
Width="{Binding ElementName=txtboxSearch, Path=ActualWidth}"
HorizontalAlignment="Stretch" x:Name="txtboxWatermark" Text="Search" Foreground="LightGray" FontStyle="Italic"/>
</VisualBrush.Visual>
</VisualBrush>
</Window.Resources>
然后您的主 XAML 完全相同,但没有 VisualBrush 定义。
<Grid Background="Tomato">
<TextBox x:Name="txtboxSearch" Height="22" Margin="3,35,111,0" TextWrapping="Wrap" VerticalAlignment="Top" BorderThickness="1"
MaxLines="1" MaxLength="256" Grid.Column="2" BorderBrush="#FF828790">
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Text" Value="{x:Static sys:String.Empty}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter Property="Background" Value="White" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</Grid>
现在您首先会看到:
当你在里面点击时:
关于c# - 在 VisualBrush 中绑定(bind)文本框的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30670911/