WPF-控件的属性值的类型转化
控件的属性值需要转成int、double进行运算的,可以使用一下方法
页面代码
<StackPanel Margin="4,0,0,0" Style="{StaticResource Form-StackPanel}">
<Label Content="替换后材料增加金额:" Style="{StaticResource StackPanel-Label-Multiple}"/>
<c1:C1MaskedTextBox Style="{StaticResource StackPanel-C1MaskedTextBox-Multiple}" Text="{Binding CurrentParamReviewItem.MaterialIncreaseCost, Mode=TwoWay}" Name="MaterialIncreaseCost" Width="130" TextChanged="C1MaskedTextBox_TextChanged" />
<Label Content="替换后加工成本增加金额:" Style="{StaticResource StackPanel-Label-Multiple}"/>
<c1:C1MaskedTextBox Style="{StaticResource StackPanel-C1MaskedTextBox-Multiple}" Text="{Binding CurrentParamReviewItem.ProcessIncreaseCost, Mode=TwoWay}" Name="ProcessIncreaseCost" Width="130" TextChanged="C1MaskedTextBox_TextChanged" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="替换后总成本变化:" Style="{StaticResource StackPanel-Label-Multiple}"/>
<c1:C1MaskedTextBox Style="{StaticResource StackPanel-C1MaskedTextBox-Multiple}" Text="{Binding CurrentParamReviewItem.TotalCost, Mode=TwoWay}" Name="TotalCost" Width="130" />
</StackPanel>
首先加入控件输入触发事件TextChanged,在对应的事件方法里面写入一下代码
private void C1MaskedTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
double? materialIncreaseCost = 0;
double? processIncreaseCost = 0;
if (!string.IsNullOrEmpty(MaterialIncreaseCost.Text)) {
materialIncreaseCost = Convert.ToDouble(MaterialIncreaseCost.Text);
}
if (!string.IsNullOrEmpty(ProcessIncreaseCost.Text))
{
processIncreaseCost = Convert.ToDouble(ProcessIncreaseCost.Text);
}
if (!materialIncreaseCost.HasValue) {
materialIncreaseCost = 0;
}
if (!processIncreaseCost.HasValue)
{
processIncreaseCost = 0;
}
double sum = materialIncreaseCost.Value + processIncreaseCost.Value;
double roundedSum = Math.Round(sum, 2, MidpointRounding.AwayFromZero);
// 现在你可以使用roundedSum变量了,比如更新UI或进行其他计算
// 例如,更新另一个控件的Text属性来显示结果
TotalCost.Text = roundedSum.ToString("N2");
}
效果