【问题标题】:Using a Converter in conjunction with a DependencyProperty将转换器与 DependencyProperty 结合使用
【发布时间】:2011-11-17 10:40:00
【问题描述】:

我在派生的 AutoCompleteBox 控件上创建了一个 DependencyProperty --> IsReadOnly

从那里,我尝试通过转换器设置值 (T/F)。根据转换器的值,我想在 DependencyProperty 的设置器中更新嵌套的 TextBox 样式。在 XAML (IsReadOnly="True") 中显式设置属性可以正常工作,并且 setter 会触发并更新样式。但是,通过转换器执行此操作不会触发 DependencyProperty 的设置器。我似乎无法在此处粘贴代码 sn-ps(第一次发帖).. 所以我会尽我所能提供一个快速的代码运行:

AutoCompleteBox 上的属性:

IsReadOnly="{Binding Converter={StaticResource IsReadOnlyVerifier}, ConverterParameter='Edit Client'}"

调用转换器,它根据用户的权限返回真或假。但是,这不会调用已注册的 DependencyProperty 的设置器。

.. 设置

        {
            if (value)
            {
                var style = StyleController.FindResource("ReadOnlyTextBox") as Style;
                TextBoxStyle = style;
            }
            else
            {
                TextBoxStyle = null;
            }
            SetValue(IsReadOnlyProperty, value);
        }

【问题讨论】:

    标签: silverlight dependencies properties dependency-properties converter


    【解决方案1】:

    这是一个经典的新手陷阱。绑定将直接使用SetValue 设置目标DependencyProperty,它们不会通过POCO 属性设置器方法分配值。

    您的IsReadOnly 属性应如下所示:-

      #region public bool IsReadOnly
      public bool IsReadOnly
      {
           get { return (bool)GetValue(IsReadOnlyProperty); }
           set { SetValue(IsReadOnlyProperty, value); }
      }
    
      public static readonly DependencyProperty IsReadOnlyProperty =
         DependencyProperty.Register(
             "IsReadOnly",
             typeof(bool),
             typeof(MyAutoCompleteBox),
             new PropertyMetaData(false, OnIsReadOnlyPropertyChanged) );
    
      private static void OnIsReadOnlyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
      {
           MyAutoCompleteBox source = d as MyAutoCompleteBox;
           source.OnIsReadOnlyChanged((bool)e.OldValue, (bool)e.NewValue);    
      }
    
      private void OnIsReadOnlyChanged(bool oldValue, bool newValue)
      {
           TextBoxStyle = newValue ? StyleControlller.FindResource("ReadOnlyTextBox") as Style ? null;
      }
      #endregion
    

    它会影响设置依赖属性时的任何其他更改,您应该在注册DependencyProperty 时向PropertyMetaData 提供PropertyChangedCallback 委托。每当使用SetValue 为该属性分配值时,都会调用此方法。

    【讨论】:

    • +1:确实很经典...我们应该准备好剪切/粘贴答案,因为这个答案经常出现:)
    • +1:我看到了几个这样处理 PropertyChangedEvent 的示例。我认为我可以“聪明”并且只需在 DP 的设置器中执行样式设置逻辑。用查理辛的话来说——双赢!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 2017-02-13
    • 2014-02-20
    • 1970-01-01
    相关资源
    最近更新 更多