120

I've a read only property I need to display in a textbox, and getting this error at runtime. I've set IsEnabled="False", IsReadOnly="True" - no luck. Other searches say the readonly should fix it, but not for me. I've got an ugly workaround by adding a dummy setter...

crthompson
  • 15,653
  • 6
  • 58
  • 80
Tony Trembath-Drake
  • 1,638
  • 3
  • 13
  • 14
  • 6
    If you do want two way binding, the property setter must be public. See http://stackoverflow.com/questions/8773150/invalidoperationexception-a-twoway-or-onewaytosource-binding-cannot-work-on-th – Colonel Panic Nov 19 '12 at 15:04
  • 1
    And from the department of the blindingly obvious, the setter must also *exist*; i.e. a property with just a get will exhibit the same issue. – noonand Oct 22 '15 at 08:52
  • @ColonelPanic "I've a read only property I need to display in a textbox" tells me that the asker isn't trying to do a two-way binding. I think he hadn't specified the binding mode and so it defaulted to TwoWay. – Stewart Dec 22 '21 at 13:44

1 Answers1

205

It's hard to guess without code, but you should be able to set the BindingMode to OneWay.

<TextBox Text="{Binding Path=MyProperty, Mode=OneWay}" />

or from code:

Binding binding = new Binding();
binding.Mode = BindingMode.OneWay;
Razzie
  • 30,834
  • 11
  • 63
  • 78
  • 32
    Yep, "Mode=OneWay" == Read Only; "Mode=OneWayToSource" == Write Only – Bryan Anderson Feb 26 '09 at 14:40
  • 1
    Please note that in .NET 4.0 there's a "bug" that OneWayToSource also does a get: http://stackoverflow.com/questions/14967667/wpf-net-4-onewaytosource-binding-to-write-only-property-works-on-some-machine – Luuk May 12 '14 at 10:36
  • Also, for TwoWay Binding on Settings see http://stackoverflow.com/a/845033/194717 – Tony Jan 08 '17 at 15:18
  • This together with https://stackoverflow.com/questions/870893/wpf-app-crashes-outside-of-visual-studio solved my problem. Thanks! One thing remains unclear: Why does my app run fine within Visual Studio despite this issue? – Stewart Dec 22 '21 at 13:43