0

Привет всем. Как то я столкнулся с необходимостью сделать placeholder в textbox на wpf. Информации на русскоязычном сегменте довольно мало. В Связи с этим хочу предложить свой вариант решения данной проблемы. Реализовано с помощью UserControl

XAML

<UserControl x:Class="Placeholder.TextBoxPlaceholder"
             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:Placeholder"
             Name="Container"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <TextBox Padding="{Binding ElementName=Container, Path=Padding}"
                 Background="Transparent" Panel.ZIndex="100" 
                 VerticalContentAlignment="Center"
                 Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" BorderThickness="0"
                 VerticalAlignment="Stretch" 
                 HorizontalAlignment="Stretch"></TextBox>
        <TextBlock Text="{Binding Placeholder}" 
                   VerticalAlignment="Center" 
                   Padding="{Binding ElementName=Container, Path=Padding}">

        </TextBlock>
    </Grid>
</UserControl>

CodeBehind

namespace Placeholder
{
    public partial class TextBoxPlaceholder : UserControl
    {
        static private string PlaceholderOldValue = string.Empty;
        public TextBoxPlaceholder()
        {
            InitializeComponent();
            DataContext = this;
        }




        public string Placeholder
        {
            get { return (string)GetValue(PlaceholderProperty); }
            set { SetValue(PlaceholderProperty, value); }
        }
        public static readonly DependencyProperty PlaceholderProperty =
            DependencyProperty.Register("Placeholder", typeof(string), typeof(TextBoxPlaceholder), new PropertyMetadata("", PlaceholderChanged));
        private static void PlaceholderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            PlaceholderOldValue = e.OldValue.ToString() != string.Empty ? e.OldValue.ToString() : ""; 
        }

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(string), typeof(TextBoxPlaceholder), new PropertyMetadata("", TextChanged));
        private static void TextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue.ToString().Length > 0)
                d.ClearValue(PlaceholderProperty);
            if (e.NewValue.ToString().Length == 0)
                d.SetValue(PlaceholderProperty, PlaceholderOldValue);
        }
    }
}

Также вот для удобства ссылка на github

https://github.com/Ascolon/TextBoxPlaceholder
12
  • Разве нельзя это сделать стилем? Зачем писать отдельный контрол для этого?
    – tym32167
    3 янв 2018 в 12:39
  • интересно а как подскажи?
    – Саске
    3 янв 2018 в 12:44
  • типа с потерей фокуса и получением фокуса что ли?
    – Саске
    3 янв 2018 в 12:45
  • Ты же плейсхолдер делаешь, тут по идее не фокус нужен, а триггер на поле Text
    – tym32167
    3 янв 2018 в 12:48
  • 1
    DataContext = this это плохая идея, т.к. DataContext – это публичное свойство, которое кто угодно может изменить, сломав тем самым ваш контрол.
    – Raider
    17 янв 2018 в 0:10

1 ответ 1

2

В вашем User Control слишком много лишнего кода. Можно было просто объявить два Dependency Property без callback-ов и установки DataContext, а в разметке привязаться на свойства User Control с помощью {Binding ..., RelativeSource={RelativeSource FindAncestor, AncestorType=local:TextBoxPlaceholder}}.

Идеологически верно было бы создать наследника TextBox (Custom Control) с новым свойством PlaceholderText и стилем в Generic.xaml, так как вы по сути расширяете стандартный TextBox новым свойством, а не просто группируете несколько отдельных Control-ов вместе (для чего собственно User Control-ы и были созданы, см. https://stackoverflow.com/questions/11247708/custom-vs-user-control).

Но проще всего создать новый стиль для TextBox, в котором в качестве placeholder текста используется стандартное свойство Tag, тем самым избежав написания какого-либо code behind в принципе.

<Style x:Key="PlaceholderTextBoxStyle" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBox}">
                <Border x:Name="border"
                        Padding="{TemplateBinding Padding}"
                        Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        SnapsToDevicePixels="True">
                    <Grid>
                        <ScrollViewer x:Name="PART_ContentHost" />
                        <TextBlock x:Name="textBlock"
                                   Margin="2,0,0,0"
                                   Foreground="{TemplateBinding BorderBrush}"
                                   IsHitTestVisible="False"
                                   Text="{Binding Tag, RelativeSource={RelativeSource TemplatedParent}}"
                                   Visibility="Collapsed" />
                    </Grid>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="Text" Value="">
                        <Setter TargetName="textBlock" Property="Visibility" Value="Visible" />
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter TargetName="border" Property="Opacity" Value="0.56" />
                    </Trigger>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter TargetName="border" Property="BorderBrush" Value="#FF7EB4EA" />
                    </Trigger>
                    <Trigger Property="IsKeyboardFocused" Value="True">
                        <Setter TargetName="border" Property="BorderBrush" Value="#FF569DE5" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Преимущество стиля в том, что его можно задать стилем по умолчанию для всех TextBox в App.xaml, не изменяя при этом остальную разметку.

Пример использования:

<TextBox Style="{StaticResource PlaceholderTextBoxStyle}" Tag="Hello world!" />

Demo

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.