【问题标题】:DataBinding on properties with no setter没有设置器的属性上的数据绑定
【发布时间】:2013-08-05 07:36:21
【问题描述】:

如何将数据绑定到只有 getter 而没有 setter 的属性,以便从 wpf 中的视图模型访问它?我正在使用 PasswordBox 并希望将其 SecureString 属性绑定到 ViewModel 属性。我该怎么做?

【问题讨论】:

  • 您想绑定到您的视图模型上的只读属性?
  • 我是 wpf 和 mvvm 的新手。我想在我的视图模型中获取密码的安全字符串并且不会设置它。
  • 您的问题是PasswordBox 控件上的SecureString 属性是只读属性,这意味着您既不能从标记也不能从代码设置。
  • 您想让PasswordBox 在XAML 的视图模型上设置SecureString 类型的属性吗?
  • 你读过this吗?

标签: c# wpf data-binding mvvm


【解决方案1】:

我使用这个类和System.Windows.Interactivity 库来访问没有设置器的属性:

public sealed class PropertyManager : TriggerAction<FrameworkElement>
{
    #region Fields

    private bool _bindingUpdating;
    private PropertyInfo _currentProperty;
    private bool _propertyUpdating;

    #endregion

    #region Dependency properties

    /// <summary>
    ///     Identifies the <see cref="Binding" /> dependency property.
    /// </summary>
    public static readonly DependencyProperty BindingProperty =
        DependencyProperty.Register("Binding", typeof(object), typeof(PropertyManager),
            new PropertyMetadata((o, args) =>
            {
                var propertyManager = o as PropertyManager;
                if (propertyManager == null ||
                    args.OldValue == args.NewValue) return;
                propertyManager.TrySetProperty(args.NewValue);
            }));

    /// <summary>
    ///     Identifies the <see cref="SourceProperty" /> dependency property.
    /// </summary>
    public static readonly DependencyProperty SourcePropertyProperty =
        DependencyProperty.Register("SourceProperty", typeof(string), typeof(PropertyManager),
            new PropertyMetadata(default(string)));

    /// <summary>
    ///     Binding for property <see cref="SourceProperty" />.
    /// </summary>
    public object Binding
    {
        get { return GetValue(BindingProperty); }
        set { SetValue(BindingProperty, value); }
    }

    /// <summary>
    ///     Name property to bind.
    /// </summary>
    public string SourceProperty
    {
        get { return (string)GetValue(SourcePropertyProperty); }
        set { SetValue(SourcePropertyProperty, value); }
    }

    #endregion

    #region Methods

    /// <summary>
    ///     Invokes the action.
    /// </summary>
    /// <param name="parameter">
    ///     The parameter to the action. If the action does not require a parameter, the parameter may be
    ///     set to a null reference.
    /// </param>
    protected override void Invoke(object parameter)
    {
        TrySetBinding();
    }

    /// <summary>
    ///     Tries to set binding value.
    /// </summary>
    private void TrySetBinding()
    {
        if (_propertyUpdating) return;
        PropertyInfo propertyInfo = GetPropertyInfo();
        if (propertyInfo == null) return;
        if (!propertyInfo.CanRead)
            return;
        _bindingUpdating = true;
        try
        {
            Binding = propertyInfo.GetValue(AssociatedObject, null);
        }
        finally
        {
            _bindingUpdating = false;
        }
    }

    /// <summary>
    ///     Tries to set property value.
    /// </summary>
    private void TrySetProperty(object value)
    {
        if (_bindingUpdating) return;
        PropertyInfo propertyInfo = GetPropertyInfo();
        if (propertyInfo == null) return;
        if (!propertyInfo.CanWrite)
            return;
        _propertyUpdating = true;
        try
        {
            propertyInfo.SetValue(AssociatedObject, value, null);
        }
        finally
        {
            _propertyUpdating = false;
        }
    }

    private PropertyInfo GetPropertyInfo()
    {
        if (_currentProperty != null && _currentProperty.Name == SourceProperty)
            return _currentProperty;
        if (AssociatedObject == null)
            throw new NullReferenceException("AssociatedObject is null.");
        if (string.IsNullOrEmpty(SourceProperty))
            throw new NullReferenceException("SourceProperty is null.");
        _currentProperty = AssociatedObject
            .GetType()
            .GetProperty(SourceProperty);
        if (_currentProperty == null)
            throw new NullReferenceException("Property not found in associated object, property name: " +
                                                SourceProperty);
        return _currentProperty;
    }

    #endregion
}

要在 XAML 中使用此类,您需要添加对 System.Windows.Interactivity 库的引用并添加以下命名空间:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:behaviors="clr-namespace:YOUR NAMESPACE WHERE YOU PUT THE PropertyManager CLASS"

您还需要指定将更新值的事件,在本例中为PasswordChanged,并指定要绑定的属性,在本例中为Password

<PasswordBox>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="PasswordChanged">
            <behaviors:PropertyManager
                Binding="{Binding Path=MyPasswordProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                SourceProperty="Password" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</PasswordBox>

这个类是通用的,可以使用任何属性,也支持双向绑定。

【讨论】:

  • 太棒了!我没有将它用于 PasswordBox,但@Victor Mukherjee 在不知情的情况下提出了一个非常好的问题,您的回答非常好。
  • 我有点嫉妒,PropertyManager 类是谁写的?
【解决方案2】:

您可以通过在绑定上将binding mode 设置为OneWay 来绑定Get only property -

<PasswordBox Text="{Binding SecureString, Mode=OneWay}"

【讨论】:

    【解决方案3】:

    在 xaml 中绑定:

    <PasswordBox Text="{Binding SecureString, Mode=OneWay}"...
    

    如果您不希望它从 xaml 绑定更改

    public string SecureString
    {
       get { return _secureString;}
       private set
       {
          if(_secureString == value) return;
          _secureString = value;
          RaisePropertyChanged(() => SecureString);
       }
    
     public void SetSecureString(string newSecureString)
     {
         SecureString = newSecureString;
     }
    

    您的 ViewModel 的使用者应该能够通过该方法设置 SecureString..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-05
      • 2017-06-29
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多