当IsFocused = false时,更改文本框的文本

时间:2012-12-18 17:33:51

标签: c# wpf textbox

如何制作以下功能:

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

感谢任何帮助。

这是我到目前为止所拥有的。但这是控制模板。我认为这个问题在这个问题上并没有那么有用,但无论如何。

  <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>

1 个答案:

答案 0 :(得分: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),但这些很容易。一旦输入了一些文本,这也将为您的文本提供数据绑定。