[WPF系列]-DataBinding 绑定计算表达式
Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualWidth,
Converter={StaticResource MathConverter},
ConverterParameter=(@VALUE-100.0)}"
Width="{Binding ElementName=RootWindow, Path=ActualWidth,
Converter={StaticResource MathConverter},
ConverterParameter=((@VALUE-200)*.3)}"
// Does a math equation on the bound value.
// Use @VALUE in your mathEquation as a substitute for bound value
// Operator order is parenthesis first, then Left-To-Right (no operator precedence)
public class MathConverter : IValueConverter
{
private static readonly char[] _allOperators = new[] { '+', '-', '*', '/', '%', '(', ')' }; private static readonly List<string> _grouping = new List<string> { "(", ")" };
private static readonly List<string> _operators = new List<string> { "+", "-", "*", "/", "%" }; #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// Parse value into equation and remove spaces
var mathEquation = parameter as string;
mathEquation = mathEquation.Replace(" ", "");
mathEquation = mathEquation.Replace("@VALUE", value.ToString()); // Validate values and get list of numbers in equation
var numbers = new List<double>();
double tmp; foreach (string s in mathEquation.Split(_allOperators))
{
if (s != string.Empty)
{
if (double.TryParse(s, out tmp))
{
numbers.Add(tmp);
}
else
{
// Handle Error - Some non-numeric, operator, or grouping character found in string
throw new InvalidCastException();
}
}
} // Begin parsing method
EvaluateMathString(ref mathEquation, ref numbers, 0); // After parsing the numbers list should only have one value - the total
return numbers[0];
} public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
} #endregion // Evaluates a mathematical string and keeps track of the results in a List<double> of numbers
private void EvaluateMathString(ref string mathEquation, ref List<double> numbers, int index)
{
// Loop through each mathemtaical token in the equation
string token = GetNextToken(mathEquation); while (token != string.Empty)
{
// Remove token from mathEquation
mathEquation = mathEquation.Remove(0, token.Length); // If token is a grouping character, it affects program flow
if (_grouping.Contains(token))
{
switch (token)
{
case "(":
EvaluateMathString(ref mathEquation, ref numbers, index);
break; case ")":
return;
}
} // If token is an operator, do requested operation
if (_operators.Contains(token))
{
// If next token after operator is a parenthesis, call method recursively
string nextToken = GetNextToken(mathEquation);
if (nextToken == "(")
{
EvaluateMathString(ref mathEquation, ref numbers, index + 1);
} // Verify that enough numbers exist in the List<double> to complete the operation
// and that the next token is either the number expected, or it was a ( meaning
// that this was called recursively and that the number changed
if (numbers.Count > (index + 1) &&
(double.Parse(nextToken) == numbers[index + 1] || nextToken == "("))
{
switch (token)
{
case "+":
numbers[index] = numbers[index] + numbers[index + 1];
break;
case "-":
numbers[index] = numbers[index] - numbers[index + 1];
break;
case "*":
numbers[index] = numbers[index] * numbers[index + 1];
break;
case "/":
numbers[index] = numbers[index] / numbers[index + 1];
break;
case "%":
numbers[index] = numbers[index] % numbers[index + 1];
break;
}
numbers.RemoveAt(index + 1);
}
else
{
// Handle Error - Next token is not the expected number
throw new FormatException("Next token is not the expected number");
}
} token = GetNextToken(mathEquation);
}
} // Gets the next mathematical token in the equation
private string GetNextToken(string mathEquation)
{
// If we're at the end of the equation, return string.empty
if (mathEquation == string.Empty)
{
return string.Empty;
} // Get next operator or numeric value in equation and return it
string tmp = "";
foreach (char c in mathEquation)
{
if (_allOperators.Contains(c))
{
return (tmp == "" ? c.ToString() : tmp);
}
else
{
tmp += c;
}
} return tmp;
}
}
参考
MathConverter - How to Do Math in XAML
[WPF系列]-DataBinding 绑定计算表达式的更多相关文章
- WPF系列——简单绑定学习
1. 绑定到元素对象.(实际项目中用处不大) 界面上两个关联的控件之间绑定,比如一个TextBlock 的FontSize和一个Slider 的Value绑定: <Slider Name=&qu ...
- [WPF系列]-DataBinding(数据绑定) 自定义Binding
自定义Binding A base class for custom WPF binding markup extensions BindingDecoratorBase Code: public c ...
- [WPF系列]-DataBinding 枚举类型数据源
public class EnumerationDataProvider : ObjectDataProvider { public Type EnumerationType { get; set; ...
- DataBinding初探 数据绑定的用法 ,import 集合类型,绑定的表达式,访问集合类型2
数据绑定的用法 import语法 <data> <import type="android.view.view"/> </data> 如 ...
- [WPF系列]从基础起步学习系列计划
引言 WPF技术已经算不什么新技术,一搜一大把关于WPF基础甚至高级的内容.之前工作中一直使用winform所以一直没有深入学习WPF,这次因项目中使用了WPF技术来实现比较酷的展示界面.我在这里只是 ...
- [WPF系列]-数据邦定之DataTemplate 对分层数据的支持
到目前为止,我们仅讨论如何绑定和显示单个集合. 某些时候,您要绑定的集合包含其他集合. HierarchicalDataTemplate 类专用于 HeaderedItemsControl 类型以显示 ...
- [WPF系列]-数据邦定之DataTemplate 根据对象属性切换模板
引言 书接上回[WPF系列-数据邦定之DataTemplate],本篇介绍如何根据属性切换模板(DataTemplate) 切换模板的两种方式: 使用DataTemplateSelecto ...
- [WPF系列]-TreeView的常用事项
引言 项目经常会用Treeview来组织一些具有层级结构的数据,本节就将项目使用Treeview常见的问题作一个总结. DataBinding数据绑定 DataTemplate自定义 <Hier ...
- WPF系列教程——(一)仿TIM QQ界面 - 简书
原文:WPF系列教程--(一)仿TIM QQ界面 - 简书 TIM QQ 我们先来看一下TIM QQ长什么样,整体可以将界面分为三个部分 TIM QQ 1. 准备 阅读本文假设你已经有XAML布局的基 ...
随机推荐
- Cocos2dx实现光影效果的两种方式
Shader 和 RenderTexture 先贴上两张效果图 (Shader) (RenderTexture) 说一下实现的原因,因为项目中需要夜景,光影的效果.最初想到使用Shader来实现.实现 ...
- log4net的使用
1.0 下载并引用 log4net.dll 2.0 修改Web.config <configuration> <configSections> <section name ...
- 第一篇:Entity Framework 简介
先从ORM说起吧,很多年前,由于.NET的开源组件不像现在这样发达,更别说一个开源的ORM框架,出于项目需要,以及当时OOP兴起(总不至于,在项目里面全是SQL语句),就自己开始写ORM框架.要开发O ...
- es6 中增强的对象字面量
http://www.cnblogs.com/Wayou/p/es6_new_features.html 对象字面量被增强了,写法更加简洁与灵活,同时在定义对象的时候能够做的事情更多了.具体表现在: ...
- UDS(ISO14229-2006) 汉译(No.3术语与定义)
下列术语适用于本文档. 3.1 integer 类型 定义正负整数的数据类型. 注:integer类型取值范围未在本文档定义. 3.2 diagnostic trouble code 由车载诊断系统获 ...
- HTML标签界里不会再用到的标签属性(一)
为了成为一名初级前端开发工程师,最近正在探寻HTML标签的众多奥秘,果不其然,让我发现了许多被“冷落”了的标签属性. 一.<!DOCTYPE> 自从HTML5流行之后,<!DOCTY ...
- 主成分分析(principal components analysis, PCA)
原理 计算方法 主要性质 有关统计量 主成分个数的选取 ------------------------------------------------------------------------ ...
- iOS通讯录整合,兼容iOS789写法,附demo
苹果的通讯录功能在iOS7,iOS8,iOS9 都有着一定的不同,iOS7和8用的是 <AddressBookUI/AddressBookUI.h> ,但是两个系统版本的代理方法有一些变化 ...
- CSS3制作动画的三个属性
CSS3属性中有关于制作动画的三个属性:Transform,Transition,Animation:我们一起学习完了Transform和Transition,让我们对元素实现了一些基本的动画效果,这 ...
- iOS 动画绘制线条颜色渐变的折线图
效果图 .................... 概述 现状 折线图的应用比较广泛,为了增强用户体验,很多应用中都嵌入了折线图.折线图可以更加直观的表示数据的变化.网络上有很多绘制折线图的demo,有 ...