DataBinding for readonly property

Is it possible to associate a field (text field) with an object that does not implement a set?

For example, I have an object that implements INotifyPropertyChanged with three fields:

public decimal SubTotal { get { return this.subTotal; } set { this.subTotal = value; this.NotifyPropertyChanged("SubTotal"); this.NotifyPropertyChanged("Tax"); this.NotifyPropertyChanged("Total"); } } public decimal Tax { get { return this.taxCalculator.Calculate(this.SubTotal, this.Region); } } public decimal Total { get { return this.SubTotal + this.Tax; } } 

I still can’t verify this, since the user interface has not been created, and before it functions, much remains to be done, but is it possible, as I have it, or is there another way?

+4
source share
3 answers

You can use properties such as a data binding source. Naturally, any such data binding should be OneWay , not TwoWay , so the changes to TextBox.Text will not try to propagate back to the property (and will not work because it was read-only).

[EDIT] The above is still done for WinForms, but you don't need to worry about OneWay/TwoWay . It will simply never try to update the source if it is read-only.

+5
source

I just tried it, it works great. The binding mechanism does not attempt to update read-only properties. This does not prevent the controls from being edited (unless you make them read-only), but the edited value is not saved

+3
source

No, since data binding is largely dependent on setting the values ​​of the properties obtained by reflection, you will have many problems with data binding and it is expected that the value will be set to the readonly property.

In this example, you cannot bind data to the Tax and Total properties.

+1
source

All Articles