1

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

以下面的代码为例...

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

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

我做错什么了??

谢谢!

4

1 回答 1

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;
}
于 2012-11-19T10:26:44.420 回答