受其他 属性 影响的绑定 DataContext 值

Binding DataContext Value that affect by other property

我已经为数据上下文创建了一个 class

public class Amt
{            
    private double _Amount = 0;
    public double Amount
    {
        get { return _Amount; }
        set { _Amount = value; }
    }   

    private double _RedeemAmount = 0;
    public double RedeemAmount
    {
        get { return _RedeemAmount; }
        set
        {
            _RedeemAmount = value;            
        }
    }

    private double _BalAmount = 0;
    public double BalAmount
    {
        get { return Amount - RedeemAmount; }
    }
}

并且我已将它绑定到位于 XAML

的 TextBox
<TextBox Name="txtAmount" Text="{Binding Amount}" FontSize="16" Margin="0,0,0,2"/>
<TextBox Name="txtRedeemAmount" Text="{Binding RedeemAmount,Mode=TwoWay}" FontSize="16" Margin="0,0,0,2" TextChanged="TxtRedeemAmount_TextChanged"/>
<TextBox Name="txtBalAmount" Text="{Binding BalAmount}" FontSize="16" Margin="0,0,0,2"/>

然后,我想要的是当我在 TextChanged 事件中更改兑换金额时,我希望余额金额也应该更改,我已经做了一些研究并尝试了一些代码,但它就是不起作用。我做错了吗?还有其他更好的方法吗?

private void TxtRedeemAmount_TextChanged(object sender, EventArgs e)
  {
    double amt = 0;
    double.TryParse(txtRedeemAmount.Text, out amt);
    Amt.RedeemAmount = amt;
   }

谢谢你的帮助!!!

要完成你想要的,你需要实现 INotifyPropertyChanged 接口。每当更改 class 的 属性 时,您应该触发 PropertyChanged 事件。

using System.ComponentModel;

public class Amt : INotifyPropertyChanged
{
    private double _Amount = 0;
    public double Amount
    {
        get { return _Amount; }
        set 
        { 
            _Amount = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Amount)));
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BalAmount)));
        }
    }

    private double _RedeemAmount = 0;
    public double RedeemAmount
    {
        get { return _RedeemAmount; }
        set
        {
            _RedeemAmount = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(RedeemAmount)));
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BalAmount)));
        }
    }

    private double _BalAmount = 0;

    public double BalAmount
    {
        get { return Amount - RedeemAmount; }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}