数据绑定到只读属性
是否可以将字段(文本框)绑定到未实现集合的属性?
例如,我有一个使用 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; }
}
我还不能完全测试它,因为尚未制作 UI,并且在该类中还有许多其他工作需要完成才能发挥作用,但这是否可能我有这样的方式,还是有其他方式?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用此类属性作为数据绑定源。 当然,任何此类数据绑定都必须是
OneWay
而不是TwoWay
,这样对TextBox.Text
的更改就不会尝试传播回该属性(由于它是只读的而失败)。[编辑]以上内容仍然适用于 WinForms,但您无需关心
OneWay/TwoWay
。 如果源是只读的,它永远不会尝试更新源。You can use such properties as source of data binding. Naturally, any such databinding would have to be
OneWay
and notTwoWay
, so that changes toTextBox.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.我刚刚尝试过,效果很好。 绑定引擎不会尝试更新只读属性。 它不会阻止编辑控件(除非将它们设置为只读),但编辑的值不会保留
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
不,由于数据绑定严重依赖于通过反射检索的属性的设置值,因此您在数据绑定和期望在只读属性上设置值时会遇到很多麻烦。
在此示例中,您将无法对
Tax
和Total
属性进行数据绑定。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
andTotal
properties.