如何计算 WPF 绑定中的值
我有一个应用程序,它使用两个滑块来生成在代码中其他地方使用的产品。我想要的是将产品值绑定到文本块或工具提示,例如,看起来像“10 x 15 = 150”。
第一部分很简单,看起来像这样:
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} x {1}">
<Binding ElementName="amount_slider" Path="Value" />
<Binding ElementName="frequency_slider" Path="Value"/>
</MultiBinding>
</TextBlock.Text>
但是有什么简单的方法可以将产品放入其中呢?
使用 Pavlo Glazkov 的解决方案,我将其修改为如下所示:
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>
谢谢!
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?
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();
}
}
And the all-important
<Window.Resources>
<local:MultiplyFormulaStringConverter x:Key="MultiplyFormulaStringConverter"/>
</Window.Resources>
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
创建一个转换器,而不是使用
StringFormat
。像这样的东西:Instead of using
StringFormat
create a converter. Something like this:您可以使用转换器并将您想要计算的两个值作为参数传递。转换器将进行计算,然后返回字符串结果。
(转换器示例此处)
You could use a converter and pass as a parameter the two values that you would like to calculate. The converter would do the calculation and then return the string result.
(Converter example here)