views:

199

answers:

3

Is it possible to bind a field (textbox) to a Property that doesn't implement a set?

For instance I have an object that implements INotifyPropertyChanged with 3 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 can't quite test this yet as the UI isn't made and there is much other work to be done in this class before it will function, but is this possible the way I have it, or is there a different way?

A: 

No, since databinding relies heavily on setting values on properties retrieved via reflection you will have a lot of trouble databinding and expecting the value to be set on a readonly property.

In this example you would be unable to databind to the Tax and Total properties.

Andrew Hare
Er, why? You can definitely use readonly properties as a _source_ in databinding, which sounds like what he's trying to do here.
Pavel Minaev
+2  A: 

You can use such properties as source of data binding. Naturally, any such databinding would have to be OneWay and not TwoWay, so that changes to TextBox.Text will not be attempted to propagate back to the property (and fail because of it being readonly).

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

Pavel Minaev
Have you tried this? The compiler will complain on you...
Reed Copsey
Uhm, no it won't...
Lasse V. Karlsen
My answer was in WPF context specifically. Yes, I've tried it - I work on a code base which uses WPF and databinding heavily, and I've wrote a lot of code binding to readonly properties myself.
Pavel Minaev
I did just edit the post to indicate that I'm working in winforms. But considering your edit I'm hopeful. I should also note that the textboxes in question will not be enabled, thus not allowing input.
SnOrfus
Just got to the point where I was able to run and test it and indeed it works as you say (I used: textbox.DataBindings.Add(new Binding("Text", objectName, "Tax"));) and it worked just fine. Thank you
SnOrfus
+1  A: 

I just tried, it works fine. The binding engine doesn't try to update the read-only properties. It doesn't prevent editing the controls (unless you make them read-only) but the edited value is not persisted

Thomas Levesque