数据绑定到只读属性

发布于 2024-08-01 20:56:35 字数 614 浏览 5 评论 0原文

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

例如,我有一个使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

标点 2024-08-08 20:56:35

您可以使用此类属性作为数据绑定源。 当然,任何此类数据绑定都必须是 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 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.

辞慾 2024-08-08 20:56:35

我刚刚尝试过,效果很好。 绑定引擎不会尝试更新只读属性。 它不会阻止编辑控件(除非将它们设置为只读),但编辑的值不会保留

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

蘸点软妹酱 2024-08-08 20:56:35

不,由于数据绑定严重依赖于通过反射检索的属性的设置值,因此您在数据绑定和期望在只读属性上设置值时会遇到很多麻烦。

在此示例中,您将无法对 TaxTotal 属性进行数据绑定。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文