c# - 在 WPF 中构建复杂的财务计算时如何管理文本框更改
问题描述
我正在使用文本框为一些复杂的财务计算构建一个 wpf 应用程序。电子表格示例
所有灰色单元格均基于公式。
我知道我可以使用 textbox_textChanges 来跟踪单个文本框的更改,我尝试创建一些通用的 textchange 方法,如下所示:
private void Txt_onTextChanged(object sender, TextChangedEventArgs e)
{
textbox.Text = int.Parse(!string.IsNullOrEmpty(textbox1.Text) ? textbox1.Text : "0") +
int.Parse(!string.IsNullOrEmpty(textbox1.Text) ? textbox1.Text : "0")
}
因为我有这么多不同的文本框和计算,所以效果不好。(当利息基础发生变化时,又更改了 3 个单元格)是否有一种有效的方法来跟踪这些变化并自动反映在另一个文本框上?我不想为每个单个Textbox创建text_TextChanges,计算方法也不一样。
解决方案
最后我找到了实现这些功能的方法。使用转换器。
public class AddListRecordsConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
decimal val = 0;
decimal result = 0;
foreach (var txt in values)
{
if (string.IsNullOrEmpty(txt.ToString())) continue;
if (decimal.TryParse(txt.ToString(), out val))
result += val;
else
return "$0.00";
}
return result.ToString();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return null;
}
}
public class InterestCalculationRecordsConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
decimal val = 0;
decimal result = 0;
List<decimal> convertedLists = new List<decimal>();
foreach (var txt in values)
{
if (string.IsNullOrEmpty(txt.ToString())) return null;
if (decimal.TryParse(txt.ToString(), out val))
//result += val;
convertedLists.Add(val);
else
return "$0.00";
}
if (convertedLists[0] == 0) return 0;
result = 1 / convertedLists[0] * convertedLists[1] * convertedLists[2] * convertedLists[3];
return result.ToString();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return null;
}
}
Xaml 如下所示。
<Page.Resources>
<local:AddListRecordsConverter x:Key="AddListRecordsConverter"></local:AddListRecordsConverter>
<local:InterestCalculationRecordsConverter x:Key="InterestCalculationRecordsConverter"></local:InterestCalculationRecordsConverter>
</Page.Resources>
文本框 Xaml 如下所示(只需发布 int 计算):
<TextBox Grid.Row="7" Grid.Column="2" Name="TxtPostJudgmentInterest" IsEnabled="False">
<TextBox.Text>
<MultiBinding Converter="{StaticResource InterestCalculationRecordsConverter}">
<Binding ElementName="TxtYearDays" Path="Text" Mode="OneWay"></Binding>
<Binding ElementName="TxtDays" Path="Text" Mode="OneWay"></Binding>
<Binding ElementName="TxtPrincipal" Path="Text" Mode="OneWay"></Binding>
<Binding ElementName="TxtInt" Path="Text" Mode="OneWay"></Binding>
</MultiBinding>
</TextBox.Text>
</TextBox>
推荐阅读
- nginx - 在 nginx 代理中设置 Tomcat
- powerbi - 面向最终用户的 Power BI 报表部署
- javascript - 使用 laravel 的 Dropzone,它显示 419 错误
- javascript - 检查 CartItem 的渲染方法
- javascript - 匹配列标题并使用 for 循环获取下面的行
- java - PDFBox - 签名后定义可视签名模板
- automation - 通过命令行触发赛普拉斯测试时,Firefox 浏览器不会关闭
- javascript - 可以从另一个模块访问模块内存空间吗?
- f# - 带有数字后缀的泛型类型参数的 F# 类型推断?
- python - EMNIST 数据集中的类问题