更改XAML中的绑定值

时间:2011-04-19 01:08:14

标签: c# wpf xaml data-binding

我需要在XAML中进行一些复杂的绑定。我有DependencyProperty typeof(double);我们将它命名为SomeProperty。在我控制的XAML代码中的某个地方,我需要使用整个SomeProperty值,只有一半,某处SomeProperty/3,等等。

我该怎么做:

<SomeControl Value="{Binding ElementName=MyControl, Path=SomeProperty} / 3"/>

:)

期待。

1 个答案:

答案 0 :(得分:7)

使用分部ValueConverter

public class DivisionConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int divideBy = int.Parse(parameter as string);
        double input = (double)value;
        return input / divideBy;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
<!-- Created as resource -->
<local:DivisionConverter x:Key="DivisionConverter"/>

<!-- Usage Example -->
<TextBlock Text="{Binding SomeProperty, Converter={StaticResource DivisionConverter}, ConverterParameter=1}"/>
<TextBlock Text="{Binding SomeProperty, Converter={StaticResource DivisionConverter}, ConverterParameter=2}"/>
<TextBlock Text="{Binding SomeProperty, Converter={StaticResource DivisionConverter}, ConverterParameter=3}"/>