2014-02-20 48 views
2

This question向我展示瞭如何爲我的文本框添加水印文本。我試圖在我的項目中實現它,但它取代了我的TextBox的背景。如何添加背景到文本框提示橫幅

因爲我的面板具有不同的顏色,所以面板顏色通過文本框顯示。我如何正確設置?

我試圖將標籤的背景設置爲白色,但由於沒有拉伸,所以不起作用。

<TextBox> 
    <TextBox.Style> 
     <Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib"> 
      <Style.Resources> 
       <VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="Uniform"> 
        <VisualBrush.Visual> 
         <!-- set the background to white --> 
         <Label Content="Search" Foreground="LightGray" Background="White"/> 
        </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> 

這給出了以下:

uniform stretched background

但設置拉伸填充給出了這樣的結果與拉伸文本:

fill stretched background

+0

是一種[水印文本](http://stackoverflow.com/a/21673718/2998271)你想實現?沒有? – har07

+0

是的。我剛剛發現這篇文章,它似乎是最簡單明瞭的解決方案,很容易理解。是的,我可以下載或重新創建更多選項,但我只是對這個特定的帖子感興趣。 – Marnix

回答

-3

您可以添加一些您的文本框後面:

<StackPanel background="white"> 
     <textbox> 
     </textbox> 
    </StackPanel> 

我認爲你的文本框的正確部分是透明的,對嗎? 我也認爲有比StackPanel更好的組件來做到這一點。

0

這可能不是最好的解決方案,但如果我的控件的行爲與他們所要求的不同,我喜歡自己創建它們。這樣我就可以完全掌握並確切地知道當我這樣做時會發生什麼。

class TextBoxWaterMark : TextBox 
{ 

#region Datafields 

private string pm_WaterMark = ""; 

#endregion 

#region Constructor 

public TextBoxWaterMark() 
{ 
} 

#endregion 

#region Control events 
protected override void OnGotFocus(RoutedEventArgs e) 
{ 
    base.OnGotFocus(e); 
    if ((string)this.Tag != "") 
    { 
    this.Foreground = new SolidColorBrush(Colors.Black); 
    this.Text = ""; 
    } 
} 

protected override void OnLostFocus(RoutedEventArgs e) 
{ 
    base.OnLostFocus(e); 
    if ((string)this.Tag != "") 
    { 
    if (this.Text == "") 
    { 
     this.Text = pm_WaterMark; 
     this.Foreground = new SolidColorBrush(Colors.Gray); 
    } 
    } 
} 
#endregion 

#region Public get and set methods 

public string WaterMark 
{ 
    get { return pm_WaterMark; } 
    set 
    { 
    pm_WaterMark = value; 
    this.Text = pm_WaterMark; 
    this.Foreground = new SolidColorBrush(Colors.Gray); 
    } 
} 
#endregion 

然後在我的XAML代碼中,我簡單地添加它,無論我想要這樣。

<Form:TextBoxWaterMark WaterMark="Insert watermark text here" /> 

希望這是你在找什麼:P