首页 > 解决方案 > 绑定受其他属性影响的 DataContext 值

问题描述

我为数据上下文创建了一个类

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;
   }

无论如何感谢您的帮助!

标签: c#wpfxamldata-bindingdatacontext

解决方案


要完成您想要的,您需要实现 INotifyPropertyChanged 接口。每当更改类的属性时,您都应该触发 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;
}

推荐阅读