DataBinding到只读属性

Ste*_*ers 4 c# data-binding properties inotifypropertychanged winforms

是否可以将字段(文本框)绑定到未实现集合的Property?

例如,我有一个实现带有3个字段的INotifyPropertyChanged的对象:

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; }
}
Run Code Online (Sandbox Code Playgroud)

我还没有完全测试这个,因为没有制作UI,并且在它运行之前还有很多其他工作需要在这个类中完成,但是这可能是我拥有它的方式,还是有不同的方式?

Pav*_*aev 5

您可以使用此类属性作为数据绑定源.当然,任何这样的数据绑定都必须是,OneWay而不是TwoWay,因此TextBox.Text不会尝试将更改传播回属性(并且由于它是只读的而失败).

[编辑]上面仍然适用于WinForms,但你不需要关心OneWay/TwoWay.如果它是只读的,它将永远不会尝试更新源.