Cysharp / R3

The new future of dotnet/reactive and UniRx.
MIT License
2.27k stars 99 forks source link

`BindableReactiveProperty` does not notify value changes in the WinForms binding system #225

Closed eudika closed 3 months ago

eudika commented 4 months ago

Phenomenon

When you bind an instance of R3.BindableReactiveProperty<T> to a WinForms control using its DataBindings property, changes on the Value property of the instance are not notified to the control. This behavior differs from Reactive.Bindings.ReactiveProperty<T>, which works as expected.

Reproduction

Here's a minimal snippet:

public partial class Form1
{
    // label1 and button1 are defined in the code behind

    private readonly BindableReactiveProperty<string> rp = new("");

    public Form1() {
        InitializeComponent();

        // Bind label1.Text to rp.Value
        label1.DataBindings.Add("Text", rp, "Value");
    }

    public void button1_Click()
    {
        // This change won't be notified to label1
        rp.Value += "X";
    }
}

Cause

The problem lies in event registration, which is eventually achieved by the AddValueChanged method of the ReflectPropertyDescriptor instance corresponding to the Value property. This method checks the following conditions:

  1. Does the component type have an event named <propertyName>Changed? (i.e. ValueChanged)
  2. Does the component type implement INotifyPropertyChanged interface?

The issue arises because the "component type" here is ReactiveProperty<T>, rather than BindableReactiveProperty<T>, since the Value property is defined in the former. Unlike the Reactive.Bindings version, where the event and the property are defined simultaneously, neither condition 1. nor 2. is met. As a result, the property is recognized as "not supporting change events." You can verify this:

var rp = new BindableReactiveProperty<string>("");
var prop = TypeDescriptor.GetProperties(rp).Find("Value", true);
Debug.WriteLine((
    prop.ComponentType.Name,    // "ReactiveProperty`1" (not Bindable)
    prop.SupportsChangeEvents   // false
));

I hope this clarifies the issue and helps you improve the package.

neuecc commented 3 months ago

Sorry for the delay in replying. Thank you for the detailed report! Thanks to you, we were able to recognize the problem and fix it. We will release it in the next release.