0

Я хочу чтобы поле ввода пароля тест стирался сзади в PasswordBox.

Пример Textbox-сом:

Когда пользователь ничего не вел

Когда пользователь что-то написал

введите сюда описание изображения

Код как такое провернуть с PasswordBox ?

<Style x:Key="BaseTextBox" TargetType="TextBox">
    <Setter Property="FontFamily" Value="{StaticResource BaseFont}" />
    <Setter Property="FontSize" Value="{StaticResource Regular}" />
    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="Background" Value="{StaticResource LightBrush}" />
    <Setter Property="Foreground" Value="Black" />
    <Setter Property="CaretBrush" Value="Black" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="TextBox">
                <Border
                    Background="{TemplateBinding Background}"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}">

                    <Grid Margin="5">
                        <ScrollViewer x:Name="PART_ContentHost" Margin="0" />
                        <TextBlock
                            x:Name="hint"
                            VerticalAlignment="Center"
                            Background="Transparent"
                            FontSize="{TemplateBinding FontSize}"
                            Foreground="Gray"
                            IsHitTestVisible="False"
                            Text="{TemplateBinding Tag}"
                            TextAlignment="{TemplateBinding TextAlignment}"
                            Visibility="Collapsed" />
                    </Grid>
                </Border>

                <ControlTemplate.Triggers>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="Text" Value="" />
                        </MultiTrigger.Conditions>
                        <Setter TargetName="hint" Property="Visibility" Value="Visible" />
                    </MultiTrigger>

                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
3

2 ответа 2

0

Хорошее решение для данного вопроса реализуется с помощью подключения пакета Material Design в NuGet. Там есть уже заготовленные стили. Тоже отличный вариант.

введите сюда описание изображениявведите сюда описание изображения

введите сюда описание изображения

 <--добавляется в пространство имён-->
    xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"

    <--сам TextBox-->   
    <TextBox materialDesign:HintAssist.Hint="Введите логин"  
    Style="{StaticResource MaterialDesignFloatingHintTextBox}" Margin=" 0,10"/>

    <--добавляется в App.xaml-->
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>
0

PasswordBoxMonitor

public class PasswordBoxMonitor : DependencyObject
    {
        public static bool GetIsMonitoring(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsMonitoringProperty);
        }

        public static void SetIsMonitoring(DependencyObject obj, bool value)
        {
            obj.SetValue(IsMonitoringProperty, value);
        }

        public static readonly DependencyProperty IsMonitoringProperty =
            DependencyProperty.RegisterAttached("IsMonitoring", typeof(bool), typeof(PasswordBoxMonitor), new UIPropertyMetadata(false, OnIsMonitoringChanged));



        public static int GetPasswordLength(DependencyObject obj)
        {
            return (int)obj.GetValue(PasswordLengthProperty);
        }

        public static void SetPasswordLength(DependencyObject obj, int value)
        {
            obj.SetValue(PasswordLengthProperty, value);
        }

        public static readonly DependencyProperty PasswordLengthProperty =
            DependencyProperty.RegisterAttached("PasswordLength", typeof(int), typeof(PasswordBoxMonitor), new UIPropertyMetadata(0));

        private static void OnIsMonitoringChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var pb = d as PasswordBox;
            if (pb == null)
            {
                return;
            }
            if ((bool)e.NewValue)
            {
                pb.PasswordChanged += PasswordChanged;
            }
            else
            {
                pb.PasswordChanged -= PasswordChanged;
            }
        }

        static void PasswordChanged(object sender, RoutedEventArgs e)
        {
            var pb = sender as PasswordBox;
            if (pb == null)
            {
                return;
            }
            SetPasswordLength(pb, pb.Password.Length);
        }
    }

Стиль для PasswordBox

  <Style   x:Key="BasePasswordBox"  TargetType="{x:Type PasswordBox}">
        <Setter Property="pas:PasswordBoxMonitor.IsMonitoring"  Value="True"/>
        <Setter Property="BorderThickness" Value="0" />
        <Setter Property="FontFamily" Value="{StaticResource BaseFont}" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type PasswordBox}">
                    <Border Name="Bd"
                    Background="{TemplateBinding Background}"
                    BorderThickness="{TemplateBinding BorderThickness}"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    SnapsToDevicePixels="true">
                        <Grid Margin="5">
                            <ScrollViewer x:Name="PART_ContentHost"
                              SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                            <TextBlock Text="Введите пароль" 
                           Foreground="Gray" 
                           Visibility="Collapsed"
                           Name="txtPrompt" />
                        </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled"
                                         Value="false">
                            <Setter TargetName="Bd"
                                            Property="Background"
                                            Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
                            <Setter Property="Foreground"
                                            Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                        </Trigger>
                        <Trigger Property="pas:PasswordBoxMonitor.PasswordLength" Value="0">
                            <Setter Property="Visibility" TargetName="txtPrompt" Value="Visible"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Вот как это выглядит на окне.

<PasswordBox   Style="{StaticResource  BasePasswordBox}"/>

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

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