How to calculate a value in WPF Binding

梦想的初衷 提交于 2019-12-22 04:05:14

问题


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!


回答1:


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>



回答2:


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)



来源:https://stackoverflow.com/questions/5057738/how-to-calculate-a-value-in-wpf-binding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!