数据库可以定义表不同列之间的计算公式,进行自动公式计算,但如何实现行上的动态公式计算呢?行由于可以动态扩展,在某些应用场景下将能很好的解决实际问题。

1、VS2012新建一个WPF应用程序WpfApp_DynCalc,并添加一个类DynCalc.cs,如下图:

2、编辑MainWindow.xaml,代码如下:

 <Window x:Class="WpfApp_DynCalc.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF动态计算示例" Height="350" Width="525">
<Grid>
<Grid.Resources>
<Style TargetType="DataGrid">
<!--网格线颜色-->
<Setter Property="CanUserResizeColumns" Value="false"/>
<Setter Property="Background" Value="#E6DBBB" />
<Setter Property="BorderBrush" Value="#d6c79b" />
<Setter Property="HorizontalGridLinesBrush">
<Setter.Value>
<SolidColorBrush Color="#d6c79b"/>
</Setter.Value>
</Setter>
<Setter Property="VerticalGridLinesBrush">
<Setter.Value>
<SolidColorBrush Color="#d6c79b"/>
</Setter.Value>
</Setter>
</Style> <!--标题栏样式-->
<!--<Style TargetType="DataGridColumnHeader" >
<Setter Property="Width" Value="50"/>
<Setter Property="Height" Value="30"/>
<Setter Property="FontSize" Value="14" />
<Setter Property="Background" Value="White" />
<Setter Property="FontWeight" Value="Bold"/>
</Style>--> <Style TargetType="DataGridColumnHeader">
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="MinWidth" Value="0" />
<Setter Property="MinHeight" Value="28" />
<Setter Property="Foreground" Value="#323433" />
<Setter Property="FontSize" Value="14" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridColumnHeader">
<Border x:Name="BackgroundBorder" BorderThickness="0,1,0,1"
BorderBrush="#e6dbba"
Width="Auto">
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ContentPresenter Margin="0,0,0,0" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<Path x:Name="SortArrow" Visibility="Collapsed" Data="M0,0 L1,0 0.5,1 z" Stretch="Fill" Grid.Column="2" Width="8" Height="6" Fill="White" Margin="0,0,50,0"
VerticalAlignment="Center" RenderTransformOrigin="1,1" />
<Rectangle Width="1" Fill="#d6c79b" HorizontalAlignment="Right" Grid.ColumnSpan="1" />
<!--<TextBlock Background="Red">
<ContentPresenter></ContentPresenter></TextBlock>-->
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Height" Value="25"/>
</Style>
<!--行样式触发-->
<!--背景色改变必须先设置cellStyle 因为cellStyle会覆盖rowStyle样式-->
<Style TargetType="DataGridRow">
<Setter Property="Background" Value="#F2F2F2" />
<Setter Property="Height" Value="25"/>
<Setter Property="Foreground" Value="Black" />
<Style.Triggers>
<!--隔行换色-->
<Trigger Property="AlternationIndex" Value="0" >
<Setter Property="Background" Value="#e7e7e7" />
</Trigger>
<Trigger Property="AlternationIndex" Value="1" >
<Setter Property="Background" Value="#f2f2f2" />
</Trigger> <Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="LightGray"/>
<!--<Setter Property="Foreground" Value="White"/>-->
</Trigger> <Trigger Property="IsSelected" Value="True">
<Setter Property="Foreground" Value="Black"/>
</Trigger>
</Style.Triggers>
</Style> <!--单元格样式触发-->
<Style TargetType="DataGridCell">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridCell">
<TextBlock TextAlignment="Center" VerticalAlignment="Center" >
<ContentPresenter />
</TextBlock>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<!--<Setter Property="Background" Value="White"/>
<Setter Property="BorderThickness" Value="0"/>-->
<Setter Property="Foreground" Value="Black"/>
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources> <DataGrid Name="dgrid" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="256" Width="498" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTextColumn Header="指标" Binding="{Binding Zb}" Width="118"/>
<DataGridTextColumn Header="值" Binding="{Binding Value}" Width="100"/>
<DataGridTextColumn Header="公式" Binding="{Binding Formula}" Width="188"/>
</DataGrid.Columns>
</DataGrid>
<Button Content="计 算" HorizontalAlignment="Left" Margin="419,281,0,0" VerticalAlignment="Top" Width="85" Click="Button_Click_1" Height="28" />
<TextBlock Name="lblResult" HorizontalAlignment="Left" Margin="28,281,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top"/> </Grid>
</Window>

3、编辑后台文件MainWindow.xaml.cs,代码如下:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes; using System.Collections.ObjectModel;
namespace WpfApp_DynCalc
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent(); ObservableCollection<Dynformula> ofs = new ObservableCollection<Dynformula>();
ofs.Add(new Dynformula { Zb = "A", Value = "", Formula = "" });
ofs.Add(new Dynformula { Zb = "B", Value = "", Formula = "2*A+1" });
ofs.Add(new Dynformula { Zb = "C", Value = "", Formula = "B*B" });
ofs.Add(new Dynformula { Zb = "D", Value = "", Formula = "C-2" });
ofs.Add(new Dynformula { Zb = "Z", Value = "", Formula = "D+C" });
this.dgrid.ItemsSource = ofs; } private void Button_Click_1(object sender, RoutedEventArgs e)
{
this.lblResult.Text = "计算...";
this.dgrid.ItemsSource= DynCalc.CalcScript(ref this.dgrid);
this.lblResult.Text = "计算完成!"; }
} public class Dynformula
{
private string zb; public string Zb
{
get { return zb; }
set { zb = value; }
}
private string value; public string Value
{
get { return this.value; }
set { this.value = value; }
}
private string formula; public string Formula
{
get { return formula; }
set { formula = value; }
} }
}

3、编辑类DynCalc.cs,代码如下:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace WpfApp_DynCalc
{
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Reflection;
using System.Globalization;
using Microsoft.CSharp;
using System.CodeDom;
using System.CodeDom.Compiler;
public static class DynCalc
{ public static ObservableCollection<Dynformula> CalcScript(ref DataGrid dgrid)
{ CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider();
ICodeCompiler objICodeCompiler = objCSharpCodePrivoder.CreateCompiler();
CompilerParameters objCompilerParameters = new CompilerParameters();
objCompilerParameters.ReferencedAssemblies.Add("System.dll");
objCompilerParameters.GenerateExecutable = false;
objCompilerParameters.GenerateInMemory = true;
CompilerResults cr = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, GenerateCode(ref dgrid));
if (cr.Errors.HasErrors)
{
Console.WriteLine("编译错误:");
foreach (CompilerError err in cr.Errors)
{
Console.WriteLine(err.ErrorText);
}
return null;
}
else
{
// 通过反射,调用实例
Assembly objAssembly = cr.CompiledAssembly;
object objDynCalc = objAssembly.CreateInstance("DynamicCodeGenerate.RunScript");
//MethodInfo objMI = objHelloWorld.GetType().GetMethod("OutPut");
//Console.WriteLine(objMI.Invoke(objHelloWorld, null)); ObservableCollection<Dynformula> ofsnew = new ObservableCollection<Dynformula>();
//循环datagrid进行公式计算并赋值
for (int i = ; i < dgrid.Items.Count; i++)
{
Dynformula item = dgrid.Items[i] as Dynformula;
if (item == null)
{
break;
}
string zb = item.Zb;
PropertyInfo pinfo = objDynCalc.GetType().GetProperty(zb);
if (pinfo != null && pinfo.CanRead) {
//获取属性get值
object obj_Name = pinfo.GetValue(objDynCalc, null);
// item.Value = obj_Name.ToString();
ofsnew.Add(new Dynformula { Zb = item.Zb, Value = obj_Name.ToString(), Formula = item.Formula});
}
}
return ofsnew;
}
}
/// <summary>
/// 计算逻辑C#脚本动态构建
/// </summary>
/// <param name="dgrid">存有指标以及指标计算公式的datagrid</param>
/// <returns>C#脚本</returns>
static string GenerateCode(ref DataGrid dgrid)
{
StringBuilder sb = new StringBuilder();
StringBuilder sb构建函数内容 = new StringBuilder();
sb.Append("using System;");
sb.Append(Environment.NewLine);
sb.Append("namespace DynamicCodeGenerate");
sb.Append(Environment.NewLine);
sb.Append("{");
sb.Append(Environment.NewLine);
sb.Append(" public class RunScript");
sb.Append(Environment.NewLine);
sb.Append(" {");
//------------------------------------------------------------
for(int i=;i<dgrid.Items.Count;i++)
{
Dynformula item = dgrid.Items[i] as Dynformula;
if (item == null)
{
break;
}
string zb = item.Zb;
sb.Append(Environment.NewLine);
sb.AppendFormat(" public double _{0};", item.Zb);
sb.Append(Environment.NewLine);
sb.AppendFormat(" public double {0}",item.Zb);
sb.Append(Environment.NewLine);
sb.Append(" {");
sb.Append(Environment.NewLine); if (item.Formula.Trim() != "")
{
sb.Append(" set{ "+item.Zb+"=value;}" );
sb.Append(Environment.NewLine);
sb.Append(" get{return "+ item.Formula + ";}");
}
else
{
sb.Append(" set{ _" + item.Zb + "=value;}");
sb.Append(Environment.NewLine);
sb.Append(" get{return _"+item.Zb+";} ");
sb.Append(Environment.NewLine);
sb构建函数内容.Append(" _" + item.Zb + "=" + item.Value);
}
sb.Append(Environment.NewLine);
sb.Append(" }");
sb.Append(Environment.NewLine);
}
//--------------------------------------------
//构造函数进行赋值
sb.Append(Environment.NewLine);
sb.Append(" public RunScript()");
sb.Append(Environment.NewLine);
sb.Append(" {");
sb.Append(Environment.NewLine);
sb.AppendFormat(" {0};",sb构建函数内容.ToString());
sb.Append(Environment.NewLine);
sb.Append(" }");
sb.Append(Environment.NewLine); //----------------------------------------------
sb.Append(Environment.NewLine);
sb.Append(" public string OutPut()");
sb.Append(Environment.NewLine);
sb.Append(" {");
sb.Append(Environment.NewLine);
sb.Append(" return \"Hello world!\";");
sb.Append(Environment.NewLine);
sb.Append(" }");
//-----------------------------------------
sb.Append(Environment.NewLine);
sb.Append(" }");
sb.Append(Environment.NewLine);
sb.Append("}"); string code = sb.ToString();
Console.WriteLine(code);
return code;
} }
}

4、运行程序,其中值列的值为初始值,点击计算后会根据公式列配置进行动态计算,初始化界面如下:

5、点击计算后界面如下:

可见现在的值是根据公式配置进行动态计算的。当然代码经过扩展还可以支持函数和简单的逻辑判断,如if ...else等。实现更强大的逻辑处理。

WPF实现强大的动态公式计算的更多相关文章

  1. 【Windows 10 应用开发】使用x:Bind标记动态获得计算结果

    UWP 在传统(WPF)的Binding标记上引入了 Bind 标记,Bind 基于编译阶段生成,因而具有较高的性能.但是,你得注意,这个性能上的优化是免去了运行阶段动态绑定的开销,这是不包括数据源的 ...

  2. [转]EXCEL如何使用动态公式

    本文转自:http://tech.cncms.com/ruanjian/office/excel/95440.html 也许大家可能还不知道Excel中的动态公式是什么,所谓的动态公式,不是普通的公式 ...

  3. WPF重写Image实现动态图片--未测试

    WPF很强大,但是当WPF的image控件遇到gif时就只读了图片的第一帧,很好很强大! WPF不屑于gif的简单动画! 幸好WPF里有MediaElement这个东西,它是对MediaPlyer的一 ...

  4. 用python实现计算1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))类似的公式计算

    作业需求: 开发一个简单的python计算器 1.实现加减乘除及拓号优先级解析 2.用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 ...

  5. 深入浅出Mybatis系列(九)---强大的动态SQL

    上篇文章<深入浅出Mybatis系列(八)---mapper映射文件配置之select.resultMap>简单介绍了mybatis的查询,至此,CRUD都已讲完.本文将介绍mybatis ...

  6. 使用Machin公式计算

    使用Machin公式计算,并使用百亿进制+末项位数控制,这里可算出数万位(比最简PI快80倍),源代码约40行,在本网页中. 计算公式 PI=16arctg(1/5)-4arctg(1/239),其中 ...

  7. c语言详解  蔡勒(Zeller)公式计算某一天是星期几  极其方便

    —— 蔡勒(Zeller)公式 ,小于等于14,即在蔡勒公式中,某年的1.2月要看作上一年的13.14月来计算,比如2003年1月1日要看作2002年的13月1日来计算):d:日:[ ]代表取整,即只 ...

  8. C#动态表达式计算

    C#动态表达式计算 应该有不少人开发过程中遇到过这样的需求,我们直接看图说话: 如上图所示,其中Entity为实体类,其中包括五个属性,该五个属性的值分别来自于数据库查询结果: 用户通过可视化界面进行 ...

  9. C#动态表达式计算(续2)

    上两篇废话太多,这一次我就不多说了,由于代码比较简单,可以直接从https://github.com/scottshare/DynamicExpress.git地址下载. 以下说明一下使用方法: Dy ...

随机推荐

  1. C++学习之重载、覆盖与隐藏

    MaiziTest12.cpp : 定义控制台应用程序的入口点. 1.重载特征 1)相同的范围(在同一个类中): 2)函数名相同: 3)参数不同: 4)virtual关键字可有可无. 2.覆盖 指的是 ...

  2. font-size:100%有什么作用

    h1,h2,h3,h4,h5,h6 {font-size:100%;font-weight:normal;} input,select,textarea,samp {font-size:100%;} ...

  3. URL中的特殊字符

    原网址:http://pichcar.iteye.com/blog/676292 URL中的特殊字符 有些符号在URL中是不能直接传递的,如果要在URL中传递这些特殊符号,那么就要使用他们的编码了.编 ...

  4. vs xamarin android SharedPreferences

    读 PreferenceManager.GetDefaultSharedPreferences(this).GetInt("uid", 0); 写 var editor = Pre ...

  5. 牛刀小试:使用Reactive Extensions(Rx),对短时间内多次发生的事件限流

    我之前有一篇文章介绍到了Reactive Extension这个组件,请参考下面的文章,其中有一些基本的概念和相关的链接 牛刀小试:使用Reactive Extensions(Rx),一行代码实现多线 ...

  6. js中的一个方法怎么将数据主动传给另一个方法

    项目有这样的一个需求,一个不断接收实时数据的有返回值的js方法Function A在运行,同时我想将接收到的这些数据进行分解提取想要的部分并传给Function B.如何实现? Function A( ...

  7. 可视化工具solo show

    辗转一圈还是回到了我魂牵梦绕的可视化上来了. 在Gephi+Netbeans上折腾了将近一个星期后,我深深的体会到个人对于代码的驾驭能力尚有提升的空间^_^,路很长,方向很重要,三思而行. 转载请标明 ...

  8. 在jfinal中使用druid,并配置查看权限

    首先导入druid包,然后配置configPlugin @Override public void configPlugin(Plugins me) { /**配置druid数据连接池插件**/ Dr ...

  9. Mac下github项目检出与提交

    项目检出 如果你的git还没有代码仓库,可以用过git的代码仓库页面新建一个你的仓库 创建git上的仓库后,我们还需要建立本地的仓库,所以打开Mac终端,建立本地仓库文件夹(这里我用HelloC),然 ...

  10. jQuery动态设置样式List item

    前段时间,Insus.NET有修改一个功能<激活当前视图菜单高亮呈现>http://www.cnblogs.com/insus/p/5287093.html 今天Insus.NET想改用另 ...