0

如何制作以下功能:

如果文本框没有聚焦,并且用户没有在那里输入任何文本,文本框应该有默认值,比如在此处输入名称...。如果用户单击该文本框,则该标签应该消失。

感谢任何帮助。

这就是我到目前为止所拥有的。但这是控制模板。我认为这对这个问题没有太大帮助,但无论如何。

  <ControlTemplate x:Key="TextBoxBaseControlTemplate" TargetType="{x:Type TextBoxBase}">
        <Border Background="{TemplateBinding Background}" 
            x:Name="Bd" BorderBrush="LightGray"
            BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="10">
            <Grid VerticalAlignment="Center">
                <ScrollViewer Margin="5 0 0 0" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Disabled"  x:Name="PART_ContentHost"/>
            </Grid>
        </Border>
        <ControlTemplate.Triggers>
            <Trigger Property="IsEnabled" Value="False">
                <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" TargetName="Bd"/>
                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
            </Trigger>
            <Trigger Property="Width" Value="Auto">
                <Setter Property="MinWidth" Value="100"/>
            </Trigger>
            <Trigger Property="Height" Value="Auto">
                <Setter Property="MinHeight" Value="20"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
4

1 回答 1

2

一种好看的方法是将默认文本设置为水印。我假设这将在 UserControl 中,所以这是我的实现

<UserControl.Resources>
    <SolidColorBrush x:Key="brushWatermarkBackground" Color="White" />
    <SolidColorBrush x:Key="brushWatermarkForeground" Color="LightSteelBlue" />
    <SolidColorBrush x:Key="brushWatermarkBorder" Color="Indigo" />

    <utilities:TextInputToVisibilityConverter x:Key="TextInputToVisibilityConverter" />
    <utilities:VisibilityToColorConverter x:Key="VisibilityToColorConverter" />
</UserControl.Resources>
<Grid>
        <TextBlock Name="MsgHeader1" HorizontalAlignment="Center" Margin="18,0,19,134" Width="308" Text="Enter Name Here..." Foreground="{StaticResource brushWatermarkForeground}" Height="46" VerticalAlignment="Bottom" Background="White">
            <TextBlock.Visibility>
                <MultiBinding Converter="{StaticResource TextInputToVisibilityConverter}">
                    <Binding ElementName="MsgHeader2" Path="Text.IsEmpty" />
                    <Binding ElementName="MsgHeader2" Path="IsFocused" />
                </MultiBinding>
            </TextBlock.Visibility>
        </TextBlock>
        <TextBox Name="MsgHeader2" TextWrapping="Wrap" Background="{Binding ElementName=MsgHeader1, Path=Visibility, Converter={StaticResource VisibilityToColorConverter}}" BorderBrush="{StaticResource brushWatermarkBorder}" Margin="18,0,19,134" Text="{Binding MessageHeader}" HorizontalAlignment="Center" Width="308" Height="46" VerticalAlignment="Bottom" />
</Grid>

显然,您必须定义自己的 ValueConverters(我的是我自己的实用程序 xmlns),但这些都很容易。一旦您输入了一些文本,这还将为您的文本提供数据绑定。

于 2012-12-18T17:43:09.347 回答