本文介绍了更改XAML中的绑定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在XAML中做一些复杂的绑定。我有一个 DependencyProperty
typeof(double)
;让我们命名为 SomeProperty
。在我控制的XAML代码的某处,我需要使用整个 SomeProperty
值,只有一半,某处 SomeProperty / 3
等等。 我该怎么做,如:
< SomeControl Value ={Binding ElementName = MyControl,Path = SomeProperty} / 3/>
:)
展望未来
解决方案
使用除法:
public class DivisionConverter:IValueConverter
{
public object Convert(object value,Type targetType,object parameter,System.Globalization.CultureInfo culture)
{
int divideBy = int.Parse(参数为string);
double input =(double)value;
return input / divideBy;
public object ConvertBack(object value,Type targetType,object parameter,System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
<! - 创建为资源 - >
< local:DivisionConverter x:Key =DivisionConverter/>
<! - 用法示例 - >
< 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}/>
I need to make some complex binding in XAML. I have a DependencyProperty
typeof(double)
; let's name it SomeProperty
. Somewhere in XAML code of my control, I need to use the whole SomeProperty
value, somewhere only a half, somewhere SomeProperty/3
, and so on.
How can I do something like:
<SomeControl Value="{Binding ElementName=MyControl, Path=SomeProperty} / 3"/>
:)
Looking forward.
解决方案
Use a division 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}"/>
这篇关于更改XAML中的绑定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!