WPF DataBinding具有简单的算术运算?

Phi*_*ght 15 data-binding wpf

我想在传入的绑定整数上添加一个常量值.事实上,我有几个地方,我想绑定到相同的源值,但添加不同的常量.所以理想的解决方案就是这样......

<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=5}"/>
<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=8}"/>
<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=24}"/>
Run Code Online (Sandbox Code Playgroud)

(注意:这是一个展示这个想法的例子,我的实际绑定方案不是TextBox的canvas属性.但这更清楚地表明了这个想法)

目前,我能想到的唯一解决方案是暴露许多不同的源属性,每个属性都将不同的常量添加到相同的内部值.所以我可以做这样的事......

<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus5}"/>
<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus8}"/>
<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus24}"/>
Run Code Online (Sandbox Code Playgroud)

但这非常严峻,因为将来我可能需要不断为新常量添加新属性.此外,如果我需要更改添加的值,我需要更改源对象,这是非常naff.

必须有比这更通用的方法吗?任何WPF专家都有任何想法?

Rac*_*hel 19

我使用MathConverter我创建的一个来完成所有简单的算术运算.转换器的代码在这里,它可以像这样使用:

<TextBox Canvas.Top="{Binding SomeValue, 
             Converter={StaticResource MathConverter},
             ConverterParameter=@VALUE+5}" />
Run Code Online (Sandbox Code Playgroud)

您甚至可以将它用于更高级的算术运算,例如

Width="{Binding ElementName=RootWindow, Path=ActualWidth,
                Converter={StaticResource MathConverter},
                ConverterParameter=((@VALUE-200)*.3)}"
Run Code Online (Sandbox Code Playgroud)


Ste*_*ner 7

我相信你可以用价值转换器做到这一点.这是一个博客条目,用于将参数传递给xaml中的值转换器.而这个博客提供了实现价值转换的一些细节.


Ian*_*kes 5

使用值转换器是解决问题的一个很好的解决方案,因为它允许您在绑定到UI时修改源值.

我在几个地方使用了以下内容.

public class AddValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        object result = value;
        int parameterValue;

        if (value != null && targetType == typeof(Int32) && 
            int.TryParse((string)parameter, 
            NumberStyles.Integer, culture, out parameterValue))
        {
            result = (int)value + (int)parameterValue;
        }

        return result;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

 <Setter Property="Grid.ColumnSpan"
         Value="{Binding 
                   Path=ColumnDefinitions.Count,
                   RelativeSource={RelativeSource AncestorType=Grid},
                   Converter={StaticResource addValueConverter},
                   ConverterParameter=1}"
  />
Run Code Online (Sandbox Code Playgroud)