Skip to content

Two-way binding modifies value of read-only property #1379

Closed
@pavelovcharov

Description

@pavelovcharov
  • .NET Core Version: 3.0.100-preview7-012821
  • Windows version: 1903 (18262.53)
  • Does the bug reproduce also in WPF for .NET Framework 4.8?: No

Problem description:
The two-way binding now changes properties with non-public setters. Is this the expected behavior? .NET Framework 472 throws InvalidOperationException, when you're trying to set two-way binding to read-only property:

System.InvalidOperationException: 'A TwoWay or OneWayToSource binding cannot work on the read-only property 'ReadonlyProperty' of type 'Test.ObjectWithReadonlyProperty'.'

Actual behavior:
The two way binding modifies property value even if it has a non-public setter
Expected behavior:
The two way binding shouldn't modify read-only properties. The InvalidOperationException should be thrown.
Minimal repro:

   class ObjectWithReadonlyProperty : INotifyPropertyChanged {
       string readonlyProperty;
       public ObjectWithReadonlyProperty(string v) {
           readonlyProperty = v;
       }
       public string ReadonlyProperty { get { return readonlyProperty; } private set { readonlyProperty = value; } }
       public event PropertyChangedEventHandler PropertyChanged;
       public void RaisePropertyChanged() {
           PropertyChanged(this, new PropertyChangedEventArgs(null)); //-V3083
       }
   }
   [TestFixture]
   public class TestFixture {
       [Test]
       public void TwoWayBindingToReadonlyProperty() {
           var btn = new Button();
           var data = new ObjectWithReadonlyProperty("12345");
           BindingOperations.SetBinding(btn, Button.ContentProperty, new Binding(nameof(ObjectWithReadonlyProperty.ReadonlyProperty)) { Mode = BindingMode.TwoWay, Source = data });
           Assert.AreEqual("12345", btn.Content);
           btn.Content = "67890";
           Assert.AreEqual("12345", data.ReadonlyProperty);
       }
   }

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugProduct bug (most likely)rank20Rank: Priority/rank on a scale of (1..100)regressionstatus: This issue is a regression from a previous build or releasetell-modeIssues and PR's that require notice to .NET Core Shiproom

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions