2012-02-23 2 views
1

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

Это прекрасно работает. (Если я привязка TextMode статической)

<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; 
} 
} 

Далее перечисление

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

+0

Что вы исключение? Сообщение? – chopikadze

+0

, он дает следующую ошибку: Set property 'QSys.Library.Controls.PasswordTextBox.TextMode' выбрал исключение. [Строка: 40 Позиция: 144] – imdadhusen

+1

Исключение всегда имеет сообщение. Я думаю, что привязка не может применяться к обычным свойствам. Вы должны изменить свой TextMode на DependencyProperty – chopikadze

ответ

1

Попробуйте изменить в своем классе 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); } 
} 

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

Основной абзац второй линии является:

A DependencyProperty supports the following capabilities in Windows Presentation Foundation (WPF):

....

  • The property can be set through data binding. For more information about data binding dependency properties, see How to: Bind the Properties of Two Controls.

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

+0

спасибо за ваше усилие, я скоро сообщу вам. – imdadhusen

+0

Очень хорошо! Я получил решение с помощью pf yours. мой голос +1 – imdadhusen

Смежные вопросы