Как связать с PasswordBox в MVVM

Используя пример:

   1   2   3   4   5   6

1  +---+---+
   |       |   
2  +   A   +---+---+
   |       | B     |
3  +       +   +---+---+
   |       |   |   |   |
4  +---+---+---+---+   +
               |       |
5              +   C   +
               |       |
6              +---+---+

1) собирают все координаты x (оба левые и правые) в список, затем сортируют его и удаляют дубликаты

1 3 4 5 6

, 2) собирают все координаты y (и вершина и нижняя часть) в список, затем сортируют его и удаляют дубликаты

1 2 3 4 6

, 3) создают 2D массив количеством разрывов между уникальными координатами x * количество разрывов между уникальными координатами y.

4 * 4

4) краска все прямоугольники в эту сетку, увеличивая количество каждой ячейки это происходит:

   1   3   4   5   6

1  +---+
   | 1 | 0   0   0
2  +---+---+---+
   | 1 | 1 | 1 | 0
3  +---+---+---+---+
   | 1 | 1 | 2 | 1 |
4  +---+---+---+---+
     0   0 | 1 | 1 |
6          +---+---+

5) суммарный итог областей ячеек в сетке, которые имеют количество, больше, чем, каждый - область перекрытия. Для лучшей эффективности в редких примерах использования можно на самом деле сохранить рабочее общее количество области, поскольку Вы красите прямоугольники, каждый раз, когда Вы перемещаете ячейку от 1 до 2.

<час>

В вопросе, прямоугольники описаны как являющийся четыре, удваивается. Удваивается обычно содержат погрешности округления, и ошибка могла бы вползти в Вашу вычисленную область перекрытия. Если легальные координаты в конечных точках, рассматривают использование целочисленного представления.

<час>

пз с помощью аппаратного акселератора в качестве в моем другом ответе не является такой потертой идеей, если разрешение приемлемо. Его также легкий реализовать в намного меньшем количестве кода, чем подход я обрисовываю в общих чертах выше. Лошади для курсов.

243
задан wonea 6 April 2017 в 22:28
поделиться

6 ответов

Sorry, but you're doing it wrong.

People should have the following security guideline tattooed on the inside of their eyelids:
Never keep plain text passwords in memory.

The reason the WPF/Silverlight PasswordBox doesn't expose a DP for the Password property is security related. If WPF/Silverlight were to keep a DP for Password it would require the framework to keep the password itself unencrypted in memory, which is considered quite a troublesome security attack vector.

The PasswordBox uses encrypted memory (of sorts) and the only way to access the password is through the CLR property.

I would suggest that when accessing the PasswordBox.Password CLR property you'd refrain from placing it in any variable or as a value for any property.
Keeping your password in plain text on the client machine RAM is a security no-no.
So get rid of that public string Password { get; set; } you've got up there.

When accessing PasswordBox.Password, just get it out and ship it to the server ASAP. Don't keep the value of the password around and don't treat it as you would any other client machine text. Don't keep clear text passwords in memory.

I know this breaks the MVVM pattern, but you shouldn't ever bind to PasswordBox.Password Attached DP, store your password in the ViewModel or any other similar shenanigans.

If you're looking for an over-architected solution, here's one:

  1. Create the IHavePassword interface with one method that returns the password clear text.
  2. Have your UserControl implement a IHavePassword interface.
  3. Register the UserControl instance with your IoC as implementing the IHavePassword interface.
  4. When a server request requiring your password is taking place, call your IoC for the IHavePassword implementation and only than get the much coveted password.

Just my take on it.

162
ответ дан 23 November 2019 в 03:10
поделиться

Как видите, я привязываю пароль к паролю, но, возможно, он привязывает его к статическому классу.

Это присоединенное свойство . Этот вид свойства может применяться к любому виду DependencyObject , а не только к типу, в котором он объявлен. Таким образом, хотя он объявлен в статическом классе PasswordHelper , он применяется к PasswordBox , в котором вы его используете.

Чтобы использовать это присоединенное свойство, вам просто нужно привязать его в свойство Password в вашей модели просмотра:

<PasswordBox w:PasswordHelper.Attach="True" 
         w:PasswordHelper.Password="{Binding Password}"/>
1
ответ дан 23 November 2019 в 03:10
поделиться

You find a solution for the PasswordBox in the ViewModel sample application of the WPF Application Framework (WAF) project.

However, Justin is right. Don't pass the password as plain text between View and ViewModel. Use SecureString instead (See MSDN PasswordBox).

0
ответ дан 23 November 2019 в 03:10
поделиться

вы можете сделать это с прикрепленным свойством, посмотрите это .. PasswordBox с MVVM

2
ответ дан 23 November 2019 в 03:10
поделиться

This works just fine for me.

<Button Command="{Binding Connect}" 
        CommandParameter="{Binding ElementName=MyPasswordBox}"/>
14
ответ дан 23 November 2019 в 03:10
поделиться

Я разместил GIST здесь , который представляет собой связываемое поле пароля.

using System.Windows;
using System.Windows.Controls;

namespace CustomControl
{
    public class BindablePasswordBox : Decorator
    {
        /// <summary>
        /// The password dependency property.
        /// </summary>
        public static readonly DependencyProperty PasswordProperty;

        private bool isPreventCallback;
        private RoutedEventHandler savedCallback;

        /// <summary>
        /// Static constructor to initialize the dependency properties.
        /// </summary>
        static BindablePasswordBox()
        {
            PasswordProperty = DependencyProperty.Register(
                "Password",
                typeof(string),
                typeof(BindablePasswordBox),
                new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback(OnPasswordPropertyChanged))
            );
        }

        /// <summary>
        /// Saves the password changed callback and sets the child element to the password box.
        /// </summary>
        public BindablePasswordBox()
        {
            savedCallback = HandlePasswordChanged;

            PasswordBox passwordBox = new PasswordBox();
            passwordBox.PasswordChanged += savedCallback;
            Child = passwordBox;
        }

        /// <summary>
        /// The password dependency property.
        /// </summary>
        public string Password
        {
            get { return GetValue(PasswordProperty) as string; }
            set { SetValue(PasswordProperty, value); }
        }

        /// <summary>
        /// Handles changes to the password dependency property.
        /// </summary>
        /// <param name="d">the dependency object</param>
        /// <param name="eventArgs">the event args</param>
        private static void OnPasswordPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs eventArgs)
        {
            BindablePasswordBox bindablePasswordBox = (BindablePasswordBox) d;
            PasswordBox passwordBox = (PasswordBox) bindablePasswordBox.Child;

            if (bindablePasswordBox.isPreventCallback)
            {
                return;
            }

            passwordBox.PasswordChanged -= bindablePasswordBox.savedCallback;
            passwordBox.Password = (eventArgs.NewValue != null) ? eventArgs.NewValue.ToString() : "";
            passwordBox.PasswordChanged += bindablePasswordBox.savedCallback;
        }

        /// <summary>
        /// Handles the password changed event.
        /// </summary>
        /// <param name="sender">the sender</param>
        /// <param name="eventArgs">the event args</param>
        private void HandlePasswordChanged(object sender, RoutedEventArgs eventArgs)
        {
            PasswordBox passwordBox = (PasswordBox) sender;

            isPreventCallback = true;
            Password = passwordBox.Password;
            isPreventCallback = false;
        }
    }
}
8
ответ дан 23 November 2019 в 03:10
поделиться
Другие вопросы по тегам:

Похожие вопросы: