将TextBox代码更改为水印TextBox的最简单方法是什么?
<TextBox Grid.Column="1" Name="txtBoxAddress" Width="200" GotKeyboardFocus="TxtBoxAddress_GotKeyboardFocus" Text="" KeyUp="TxtBoxAddress_KeyUp"></TextBox>
答案 0 :(得分:0)
选项一将是use a background image,如MSDN中所述。如果你想使用绑定,这可能是最好的方法。
<强> XAML 强>
<StackPanel>
<TextBox Name="myTextBox" TextChanged="OnTextBoxTextChanged" Width="200">
<TextBox.Background>
<ImageBrush ImageSource="TextBoxBackground.gif" AlignmentX="Left" Stretch="None" />
</TextBox.Background>
</TextBox>
</StackPanel>
</Page>
<强>代码强>
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace SDKSample
{
public partial class TextBoxBackgroundExample : Page
{
void OnTextBoxTextChanged(object sender, TextChangedEventArgs e)
{
if (myTextBox.Text == "")
{
// Create an ImageBrush.
ImageBrush textImageBrush = new ImageBrush();
textImageBrush.ImageSource =
new BitmapImage(
new Uri(@"TextBoxBackground.gif", UriKind.Relative)
);
textImageBrush.AlignmentX = AlignmentX.Left;
textImageBrush.Stretch = Stretch.None;
// Use the brush to paint the button's background.
myTextBox.Background = textImageBrush;
}
else
{
myTextBox.Background = null;
}
}
}
或者您可以使用this codeproject article中所述的BooleanToVisibilityConverter。