2012-12-18 96 views
0

我怎麼能做出以下功能:IsFocused時改變文本框,文本=假

如果文本框不集中,和用戶沒有輸入任何文字在那裏,文本框應該有默認值,像輸入名稱這裏...。如果用戶點擊該文本框,該標籤應該消失。

感謝任何幫助。

這是我到目前爲止。但這是控制模板。我認爲這個問題並沒有那麼有用,但無論如何。

<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

可能的重複http://stackoverflow.com/questions/384264/how-do-you-implement-default-text-for-a-search-box-in-wpf? – IronMan84

+1

ups,我沒有找到那個討論。謝謝 – Vlad

回答

2

一個好看的方法是讓您的默認文本水印。我認爲這將是在用戶控件所以這裏是我的執行

<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),但這些都是很容易做到。一旦您輸入了一些內容,這也會爲您提供一個數據綁定。

+0

感謝您的回覆 – Vlad