如何引发属性更改事件以触发其他属性

时间:2018-11-27 03:00:26

标签: c# wpf inotifypropertychanged

我不确定标题是否正确。我具有绑定到2个文本框的两个double属性,当一个属性更改时,我想计算它们的总数。 RemainingBalance属性是我计算并显示总计的地方。我认为下面的代码将在UI中更改GiftSold或GiftUsed值时进行计算。我什至尝试了双向模式,但仍然无法正常工作。

    private double _giftSold;
    public double GiftSold
    {
        get { return _giftSold; }
        set
        {
            if (value != _giftSold)
            {
                _giftSold = value;
                OnPropertyChanged("GiftSold");
                OnPropertyChanged("RemainingBalance");
            }
        }
    }

    private double _giftUsed;
    public double GiftUsed
    {
        get { return _giftUsed; }
        set
        {
            if (value != _giftUsed)
            {
                _giftUsed = value;
                OnPropertyChanged("GiftUsed");
                OnPropertyChanged("RemainingBalance");
            }
        }
    }

    public double RemainingBalance
    {
        get { return GiftSold - GiftUsed; }
    }

这是我的xaml

<StackPanel Orientation="Horizontal">
    <TextBlock Text="Gift Sold  "/>
    <TextBox Text="{Binding GiftSold, Mode=TwoWay}"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
    <TextBlock Text="Gift Used  "/>
    <TextBox Text="{Binding GiftUsed, Mode=TwoWay}"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
    <TextBlock Text="Remain Balance  "/>
    <TextBlock Text="{Binding RemainBalance}"/>
</StackPanel>

1 个答案:

答案 0 :(得分:0)

    private double _giftSold;
public double GiftSold
{
    get { return _giftSold; }
    set
    {
        if (value != _giftSold)
        {
            _giftSold = value;
            CalculateRemainingBalance();
            OnPropertyChanged("GiftSold"); 
        }
    }
}

private double _giftUsed;
public double GiftUsed
{
    get { return _giftUsed; }
    set
    {
        if (value != _giftUsed)
        {
            _giftUsed = value;
                CalculateRemainingBalance();
            OnPropertyChanged("GiftUsed");
        }
    }
}

private double _RemainingBalance;
public double RemainingBalance
{
    get { return _RemainingBalance }
}

private void CalculateRemainingBalance()
{
_RemainingBalance = GiftSold - GiftUsed;
 OnPropertyChanged("RemainingBalance");
}

尝试一下。