开发者

How to perform WPF Data binding, if Two TextBox's values depends on each other(Discount Amount and Discount Percentage)

I have Total Amount Stored in Some Variable,Two TextBoxes,

  1. Discount Percentage
  2. Discount Amount

that shoud be calculated form amount variable, I want Effect like if i change percentage then dis开发者_JS百科count amount shoud get reflected and if i changed discount amount then percentage should get reflected using DataBinding in WPF


You have a linkage between two properties in your view-model. The view doesn't need to know anything about this linkage. If you change the rate in the user interface, the binding will propagate that value back to the view-model. But now you have an inconsistency: the discount is wrong.

The view-model can enforce any relationships it wants between the properties that it exposes as long as it properly notifies the binding subsystem of any property changes. So to handle this case, just modify the setter in view-model for rate so that it sets the rate as usual but also sets a new discount. Then raise property notification for both properties. Now the view-model is consistent again. Likewise but in reverse when you are changing the discount.

Here is a primitive view-model that demonstrates this approach:

public class DiscountViewModel : INotifyPropertyChanged
{
    private double total;
    private double rate;
    private double discount;

    public double Total
    {
        get { return total; }
        set { total = value; OnPropertyChanged("Total"); }
    }

    public double Rate
    {
        get { return rate; }
        set
        {
            rate = value;
            discount = total * rate;
            OnPropertyChanged("Rate");
            OnPropertyChanged("Discount");
        }
    }

    public double Discount
    {
        get { return discount; }
        set
        {
            discount = value;
            rate = discount / total;
            OnPropertyChanged("Rate");
            OnPropertyChanged("Discount");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜