我正在使用 WPF 开发 C# .NET 6.0 项目,并且有以下场景:
我的 WPF 应用程序中有两个文本框:
<StackPanel>
<Label>Fee Percentage:</Label>
<TextBox Text="{Binding ContractExtension.FeesPercentage, UpdateSourceTrigger=PropertyChanged}"></TextBox>
</StackPanel>
<StackPanel>
<Label>Amount in $</Label>
<TextBox Text="{Binding FeesAmount, Mode=OneWay}" IsReadOnly="True"></TextBox>
</StackPanel>
第二个文本框的值取决于第一个文本框的值:
public class MainViewModel : BaseViewModel
{
private ContractExtension contractExtension;
public ContractExtension ContractExtension
{
get { return contractExtension; }
set
{
contractExtension = value;
OnPropertyChanged(nameof(ContractExtension));
OnPropertyChanged(nameof(FeesAmount));
}
}
public decimal FeesAmount
{
get
{
decimal feesAmount = Toolbox.GetContractGivenValue(contract, false) * ContractExtension.FeesPercentage / 100;
return feesAmount;
}
}
}
public abstract class BaseViewModel : INotifyPropertyChanged
{
#region Attributes
private Window parentWindow;
#endregion Attributes
#region Properties
public Window ParentWindow
{
get
{
return parentWindow;
}
set
{
parentWindow = value;
SetParentWindow(value);
}
}
public abstract void SetParentWindow(Window parentWindow);
public SearchBoxViewModel SearchBoxViewModel { get; }
#endregion Properties
public event PropertyChangedEventHandler? PropertyChanged;
public abstract void ResetData();
protected static ExceptionManager exceptionManager;
public BaseViewModel()
{
exceptionManager = new ExceptionManager();
SearchBoxViewModel = new SearchBoxViewModel();
}
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void RefreshProperty(string propertyName)
{
OnPropertyChanged(propertyName);
}
}
但是,当我修改
FeesPercentage
的值时,FeesAmount
在界面中并没有更新。 ContractExtension
是实体模型,Toolbox.GetContractGivenValue
是用于计算FeesAmount
的效用方法。
我检查过的事情:
ContractExtension
实施 INotifyPropertyChanged
DataContext
设置正确ContractExtension
的setter在FeesPercentage
改变时被调用我的代码中是否还应该检查或修改其他内容,以使
FeesAmount
在 FeesPercentage
更改时在界面中正确更新?
我不明白的是,在我的应用程序的其他地方,这就是我所做的并且它有效,但它在这里不起作用...我调试了
ContractExtension
get,set 它进入了设置初始化,但是每当我在文本框中编辑 FeesPercentage
的值时,它都不会触发 ContractExtension
组,因此不会执行 OnPropertyChanged(FeesAmount)
。
看来你需要这样做:
public ContractExtension ContractExtension
{
get { return contractExtension; }
set
{
//remove event listener from previous instance
if (contractExtension is not null)
contractExtension.PropertyChanged -= ContractExtension_OnPropertyChanged;
contractExtension = value;
OnPropertyChanged(nameof(ContractExtension));
OnPropertyChanged(nameof(FeesAmount));
//listen to the propertychanged event of your contractExtension
contractExtension.PropertyChanged += ContractExtension_OnPropertyChanged;
}
}
private void ContractExtension_OnPropertyChanged(object sender, PropertyChangedEventArgs args)
{
//trigger FeesAmount if FeesPercentage changes
if (args.PropertyName == nameof(ContractExtension.FeesPercentage))
OnPropertyChanged(nameof(FeesAmount));
}