TextBoxPlaceholder XAML WPF

259
04 января 2018, 20:30

Привет всем. Как то я столкнулся с необходимостью сделать 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
READ ALSO
UWP C# Как считать часть файла?

UWP C# Как считать часть файла?

Нужно считать, например, один символ или строку до разделителяПодскажите, как это сделать?

220
Как убрать класс из подсказок Resharper&#39;а?

Как убрать класс из подсказок Resharper'а?

Иногда когда я пишу код в реализации репозитория мне Resharper предлагает на выбор одноимённый класс из папки Migration:

207