Доброго времени суток, всем. Я так понимаю, в WPF нет контрола, который будет похож на TextBox и иметь свойство placeholder'а. В WinForms я писал такой контрол, и зайдествовал, помню, WinAPI. Я так понял, что в WPF задействовать какое-либо низкое API для отображения PlaceHolder'а в TextBox нет необходимости, поэтому сделал следующее: 1. Создал UserControl:
<UserControl x:Class="PTRCPriceCalculator.InputBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:PTRCPriceCalculator"
mc:Ignorable="d"
d:DesignHeight="40" d:DesignWidth="300">
<!-- InputBox template -->
<UserControl.Template>
<ControlTemplate TargetType="{x:Type UserControl}">
<Grid>
<!-- Inner texbox -->
<TextBox HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
Background="{TemplateBinding Background}"
Foreground="{TemplateBinding Foreground}"
FontFamily="{TemplateBinding FontFamily}"
FontSize="{TemplateBinding FontSize}"
BorderThickness="0">
<!-- Style for the inner textbox -->
<TextBox.Style>
<Style TargetType="{x:Type TextBoxBase}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBoxBase}">
<Grid>
<!-- Standard textbox role -->
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<ScrollViewer x:Name="PART_ContentHost" Focusable="False" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
</Border>
<!-- Place holder -->
<TextBlock IsHitTestVisible="false"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
FontFamily="{TemplateBinding FontFamily}"
FontSize="{TemplateBinding FontSize}"
Text="{Binding PlaceHolder, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}"
Padding="{TemplateBinding Padding}">
<!-- Place holder style -->
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource TemplatedParent}}" Value="">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" TargetName="border" Value="0.56"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="BorderBrush" TargetName="border" Value="#FF7EB4EA"/>
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter Property="BorderBrush" TargetName="border" Value="#FF569DE5"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</TextBox.Style>
</TextBox>
</Grid>
</ControlTemplate>
</UserControl.Template>
</UserControl>
В codebehind определил два свойства зависимости:
public static readonly DependencyProperty PlaceHolderProperty = DependencyProperty.Register(
"PlaceHolder",
typeof( string ),
typeof( InputBox ) );
public string PlaceHolder
{
get { return (string)GetValue( PlaceHolderProperty ); }
set { SetValue( PlaceHolderProperty, value ); }
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof( string ),
typeof( InputBox ) );
public string Text
{
get { return (string)GetValue( TextProperty ); }
set { SetValue( TextProperty, value ); }
}
Все здорово, PlaceHolder появляется. Но я не могу понять, как мне делегировать свойство Text к свойству Text моего TextBox'а, который находится внутри Template моего UserControl'а? И еще пару незначительных вопросов: 1. Насколько эффективнее/неэффективнее использовать такой способ создания TextBox'а с placeholder'ом по сравнению с WinAPI? 2. Для отображения PlaceHolder'а, как Вы видите, я определил TextBlock, который отображается/не отображается в зависимости от значения Text в TextBox. Суть в том, что, отображение PlaceHolder'а в TextBlock и реального текста в TextBox не совпадают на несколько пикселей, хотя все проверено мной. Даже Border у TextBox'а убрал, все равно не совпадает. Можно ли это исправить, или лучше забить на это?:)