在不破坏绑定的情况下更改 属性 值以支持双向绑定

Change property value without destroying binding to support two-way binding

我想创建一个自定义组件,它允许使用以下(传统)设置进行双向绑定:

// main.qml
property var someStoredValue: someInitialValue // may be C++ property in real application
MyCustomComponent
{
    myProperty: someStoredValue // this binding will be destroyed on user input
    onMyPropertyChanged: someStoredValue = myProperty
}

// MyCustomComponent.qml
Item
{
    property var myProperty: null
    MouseArea
    {
        anchors.fill: parent
        onClicked: myProperty = "some text or other value" // breaks the binding set in main.cpp
    }
}

MyCustomComponent 应该能够更新 myProperty(以编程方式),而不会破坏 someStoredValuemyProperty 之间的绑定。我怎样才能改变 MyCustomComponent 的实现来实现我的目标?

一个解决方案是使用 Binding 对象更新 MyCustomComponent 内的 myProperty,而不是直接更改值:

// MyCustomComponent.qml
Item
{
    property var myProperty: null
    Binding on myProperty
    {
        id: myPropertyUpdater
        function set(newValue) {value = newValue; when = true; when = false;}
        when: false
    }

    MouseArea
    {
        anchors.fill: parent
        onClicked: myPropertyUpdater.set("some text or other value")
    }
}

诀窍是将 Bindingwhen 属性 设置为 true,以传播新值。停用 Binding (when = false;) 后,将恢复之前的任何直接绑定,如 docs:

中所述

When the binding becomes inactive again, any direct bindings that were previously set on the property will be restored.