如何计算在WPF值绑定 [英] How to calculate a value in WPF Binding
本文介绍了如何计算在WPF值绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个使用两个滑块来生成在code在其他地方使用的产品的应用程序。我想是有绑定到一个文本块或提示产品的价值,例如,类似于10×15 = 150。
I have an app which uses two sliders to generate a product used elsewhere in the code. What I would like is to have the product value bound to a textblock or tooltip, for example, to look something like "10 x 15 = 150".
第一部分是容易的,看起来像这样:
The first part is easy, and looks like this:
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} x {1}">
<Binding ElementName="amount_slider" Path="Value" />
<Binding ElementName="frequency_slider" Path="Value"/>
</MultiBinding>
</TextBlock.Text>
但是,什么是一个不错的简单的方法,在那里得到的,以及产品?
But what's a nice easy way to get the product in there as well?
使用帕夫洛Glazkov的解决方案,我修改它看起来是这样的:
Using Pavlo Glazkov's solution, I modified it to look like this:
public class MultiplyFormulaStringConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var doubleValues = values.Cast<double>().ToArray();
double x = doubleValues[0];
double y = doubleValues[1];
var leftPart = x.ToString() + " x " + y.ToString();
var rightPart = (x * y).ToString();
var result = string.Format("{0} = {1}", leftPart, rightPart);
return result;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
和所有重要的
<Window.Resources>
<local:MultiplyFormulaStringConverter x:Key="MultiplyFormulaStringConverter"/>
</Window.Resources>
谢谢!
推荐答案
而不是使用的StringFormat
创建一个转换器。事情是这样的:
Instead of using StringFormat
create a converter. Something like this:
public class MultiplyFormulaStringConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var doubleValues = values.Cast<double>().ToArray();
var leftPart = string.Join(" x ", doubleValues);
var rightPart = doubleValues.Sum().ToString();
var result = string.Format("{0} = {1}", leftPart, rightPart);
return result;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
<TextBlock.Text>
<MultiBinding Converter="{StaticResource MultiplyFormulaStringConverter}">
<Binding ElementName="amount_slider" Path="Value" />
<Binding ElementName="frequency_slider" Path="Value"/>
</MultiBinding>
</TextBlock.Text>
这篇关于如何计算在WPF值绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文