【问题标题】:Internal management of DependencyProperty value and Changed callbacksDependencyProperty 值和更改回调的内部管理
【发布时间】:2012-11-19 07:56:48
【问题描述】:

我认为这是一个关于如何管理依赖属性的基本误解,但我似乎找不到一个明确的例子来纠正我。

以下面的代码为例……

public class MyControl
{
    public static readonly DependencyProperty ExpressionProperty = 
                                    DependencyProperty.Register("Expression",
                                    typeof (Expression),
                                    typeof (MyControl),
                                    new PropertyMetadata(ExpressionChanged));

    public Expression Expression
    {
        get { return (Expression)GetValue(ExpressionProperty); }
        set { SetValue(ExpressionProperty, value); }
    }

    private static void ExpressionChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    {
        ... Must respond to external change of property
        ... Update UI to reflect external change to property
    }

    private void RespondToInput()
    {
        ... Do something to expression, add new elements or something
        ... Now expression has changed so I want to update the dependency property
        ... so datacontext gets new value.
        SetValue(ExpressionProperty, updatedExpression);
    }
}

我不明白的是,当我执行 RespondToInput 工作时,我现在想更新 DependencyProperty,但如果我这样做了,就会调用 PropertyChanged 回调,此时我转了一圈,现在开始更新UI,即使我有效地从 UI 发起了更改。

我不知道这是否足够有意义。

我做错了什么??

谢谢!

【问题讨论】:

  • 也许只是一个错字。您将 DependencyProperty.Register 的 ownerType 参数设置为 ExpressionRichTextBox,尽管该属性是在类 MyControl 中定义的。
  • 对不起,错字!解决了谢谢!

标签: wpf dependency-properties


【解决方案1】:

您无法阻止在属性值更改时调用 PropertyChangedCallback。您可以做的是不对内部属性更改做出反应

private bool isInternalExpressionChanged;

private static void ExpressionChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
    if (!isInternalExpressionChanged)
    {
        ...
    }
}

private void RespondToInput()
{
    ...
    isInternalExpressionChanged = true;
    SetValue(ExpressionProperty, updatedExpression);
    isInternalExpressionChanged = false;
}

【讨论】:

  • 这正是我所做的,但感觉完全不对。我一直在想我没有正确理解如何处理公共属性、依赖属性和值的内部管理。也许这是唯一的方法,这是普遍共识吗?
  • “公共属性”依赖属性并且(来自应用程序代码)内部值。你根本分不清。
  • 我很高兴你想出了与我相同的方法,至少我并没有完全偏离基础。它仍然感觉好像不太正确,但它确实有效,所以现在一切都很好!感谢您的帮助/安慰。
猜你喜欢
  • 1970-01-01
  • 2016-07-21
  • 2011-01-04
  • 2019-01-16
  • 2017-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-10
相关资源
最近更新 更多