在实际的开发中,我们经常会遇到Binding的Source和Target是不同的类型,如下面的例子,我们需要将一个Button的IsEnable属性绑定到一个TextBox的Text属性,实现的效果是当TextBox的输入为空时,Button不可用。
Bingding中有一个叫做Converter的属性,顾名思义,就是转换器的意思,就可以帮助我们实现这种效果。
首先,我们需要自己写一个Converter,方法是创建一个类,继承IValueConverter接口:
public class StringToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return false;
if (value is string&&
string.IsNullOrEmpty((string)value)==false)
{
return true;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
在接口函数Convert中,我们进行从Binding的Source到Target类型的转换,在这里我们判断value是否为空,如果为空返回false,否则返回true;在ConvertBack中我们可以实现Binding的Target到Source类型的转换,同Convert的转换方法类似,在这里并没有实现,而是抛出了一个不用处理的NotImplementedException异常。
接下来,我们在Xmal文件中,实现Binding,代码如下:
<Window x:Class="_6_34.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:_6_34"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:StringToBoolConverter x:Key="s2b"/>
</Window.Resources>
<Grid>
<TextBox Height="23" HorizontalAlignment="Left" Margin="160,82,0,0" Name="textBox1" VerticalAlignment="Top" Width="120"
/>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="180,178,0,0" Name="button1" VerticalAlignment="Top" Width="75"
IsEnabled="{Binding Text,Converter={StaticResource s2b},ElementName=textBox1}"/>
</Grid>
</Window>
我们先在Window.Resources中创建了一个StringToBoolConverter对象,键值为s2b,然后将Button的
IsEnabled绑定到TextBox的Text属性上,Converter设置静态资源s2b,这样就实现了Binding的数据转换。
运行效果如下:
当TextBox为空时,Button不可用:
当当TextBox不为空时,Button自动变为可用: