我需要在 XAML 中进行一些复杂的绑定(bind)。我有一个 DependencyProperty
typeof(double)
;我们将其命名为 SomeProperty
。在我的控件的 XAML 代码中的某处,我需要使用整个 SomeProperty
值,某处只使用一半,某处 SomeProperty/3
,等等。
我该如何做:
<SomeControl Value="{Binding ElementName=MyControl, Path=SomeProperty} / 3"/>
:)
期待。
最佳答案
使用除法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}"/>
关于c# - 更改 XAML 中的绑定(bind)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5710521/