DependencyProperty值和Changed回调的内部管理

时间:2012-11-19 07:56:49

标签: wpf dependency-properties

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

以下面的代码为例......

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发起了更改。

我不知道这是否足够了。

我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分: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;
}