Ошибка в привязке пользовательского свойства текстового поля - PullRequest
1 голос
/ 23 февраля 2012

Я создал пользовательское текстовое поле в Silverlight 4, MVVM и PRISM 4. Пользовательское текстовое поле имеет динамическое поведение, оно динамически устанавливает для TextMode либо пароль, либо текст.

Это работаетидеально.(если я привязан к TextMode static)

<control:PasswordTextBox x:Name="customTextBox2" Width="100" Height="30" Grid.Row="4" Grid.Column="1" Text="{Binding Email}"  TextMode="Password"/>

Это дает мне ошибку (если я связываюсь с динамическим)

<control:PasswordTextBox x:Name="customTextBox1" Width="100" Height="30" Grid.Row="4" Grid.Column="1" Text="{Binding Email}"  TextMode="{Binding WritingMode}"/>

ниже мой код ViewModel

[Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class UserRightsViewModel : NotificationObject, IRegionMemberLifetime
    {
 private Mode _writingMode = Mode.Text;
public Mode WritingMode
        {
            get { return _writingMode; }
            set
            {
                _writingMode = value; RaisePropertyChanged("WritingMode");
            }
        }

[ImportingConstructor]
        public UserRightsViewModel(IEventAggregator eventAggregator, IRegionManager regionManager)
        {
UserSecurity security = new UserSecurity();
            FormSecurity formSecurity = security.GetSecurityList("Admin");
formSecurity.WritingMode =  Mode.Password;
}
}

следующим является enum

namespace QSys.Library.Enums
{
    public enum Mode
    {
        Text,
        Password
    }
}

следующий код для Custom PasswordTextBox

namespace QSys.Library.Controls
{
    public partial class PasswordTextBox : TextBox
    {
        #region Variables
        private string _Text = string.Empty;
        private string _PasswordChar = "*";
        private Mode _TextMode = Mode.Text;
        #endregion

        #region Properties
        /// <summary>
        /// The text associated with the control.
        /// </summary>
        public new string Text
        {
            get { return _Text; }
            set
            {
                _Text = value;
                DisplayMaskedCharacters();
            }
        }
        /// <summary>
        /// Indicates the character to display for password input.
        /// </summary>
        public string PasswordChar
        {
            get { return _PasswordChar; }
            set { _PasswordChar = value; }
        }
        /// <summary>
        /// Indicates the input text mode to display for either text or password.
        /// </summary>
        public Mode TextMode
        {
            get { return _TextMode; }
            set { _TextMode = value; }
        }
        #endregion

        #region Constructors
        public PasswordTextBox()
        {
            this.TextChanged += new TextChangedEventHandler(PasswordTextBox_TextChanged);
            this.KeyDown += new System.Windows.Input.KeyEventHandler(PasswordTextBox_KeyDown);
            this.Loaded += new RoutedEventHandler(PasswordTextBox_Loaded);
        }
        #endregion

        #region Event Handlers
        void PasswordTextBox_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            //this.TextChanged += ImmediateTextBox_TextChanged;
        }
        public void PasswordTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (base.Text.Length >= _Text.Length) _Text += base.Text.Substring(_Text.Length);
            DisplayMaskedCharacters();
        }
        public void PasswordTextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            int cursorPosition = this.SelectionStart;
            int selectionLength = this.SelectionLength;
            // Handle Delete and Backspace Keys Appropriately
            if (e.Key == System.Windows.Input.Key.Back || e.Key == System.Windows.Input.Key.Delete)
            {
                if (cursorPosition < _Text.Length)
                    _Text = _Text.Remove(cursorPosition, (selectionLength > 0 ? selectionLength : 1));
            }
            base.Text = _Text;
            this.Select((cursorPosition > _Text.Length ? _Text.Length : cursorPosition), 0);
            DisplayMaskedCharacters();
        }
        #endregion

        #region Private Methods
        private void DisplayMaskedCharacters()
        {
            int cursorPosition = this.SelectionStart;
            // This changes the Text property of the base TextBox class to display all Asterisks in the control
            base.Text = new string(_PasswordChar.ToCharArray()[0], _Text.Length);
            this.Select((cursorPosition > _Text.Length ? _Text.Length : cursorPosition), 0);
        }
        #endregion

        #region Public Methods
        #endregion
    }
}

Я получаю следующую ошибку, если я связываюсь с динамически.

Установка свойства 'QSys.Library.Controls.PasswordTextBox.TextMode' вызвала исключение.[Строка: 40 Позиция: 144]

Ваш ответ приветствуется.Заранее спасибо.Imdadhusen

1 Ответ

1 голос
/ 23 февраля 2012

Попробуйте изменить свой класс PasswordTextBox

public Mode TextMode
{
    get { return _TextMode; }
    set { _TextMode = value; }
}

до

public static readonly DependencyProperty TextModeProperty =
            DependencyProperty.Register("TextMode", typeof(Mode), typeof(PasswordTextBox), new PropertyMetadata(default(Mode)));

public Mode TextMode
{
    get { return (Mode) GetValue(TextModeProperty); }
    set { SetValue(TextModeProperty, value); }
}

Вы можете прочитать больше здесь:

Основной абзац второй ссылки:

DependencyProperty поддерживает следующие возможности в Windows Фонд презентаций (WPF):

....

  • Свойство может быть установлено через привязку данных. Для получения дополнительной информации о свойствах зависимости привязки данных см. Как: Привязать Свойства двух элементов управления.

Я предоставляю ссылки для WPF, но в основном для Silverlight это то же самое

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...