透かしテキストボックスの代わりに、ビヘイビアーを使用できます。
System.Windows.Interactivity
参照する必要があります。
例:
Xaml:
<Window x:Class="WatermarkTextBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:WatermarkTextBox="clr-namespace:WatermarkTextBox" Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBox Grid.Row="0" Width="300" Height="30">
<i:Interaction.Behaviors>
<WatermarkTextBox:WatermarkBehavior />
</i:Interaction.Behaviors>
</TextBox>
<TextBox Grid.Row="1" Width="300" Height="30" />
</Grid>
</Window>
行動:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
namespace WatermarkTextBox
{
public class WatermarkBehavior : Behavior<TextBox>
{
private string _value = string.Empty;
protected override void OnAttached()
{
AssociatedObject.GotFocus += OnGotFocus;
AssociatedObject.LostFocus += OnLostFocus;
}
protected override void OnDetaching()
{
AssociatedObject.GotFocus -= OnGotFocus;
AssociatedObject.LostFocus -= OnLostFocus;
}
private void OnGotFocus(object sender, RoutedEventArgs e)
{
AssociatedObject.Text = _value;
}
private void OnLostFocus(object sender, RoutedEventArgs e)
{
_value = AssociatedObject.Text;
AssociatedObject.Text = string.Format("Watermark format for: {0}", _value);
}
}
}