WPF中的binding(十一)
在实际的开发中,我们经常会遇到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自动变为可用:
相关知识
双十一活动策划
“双十一”的套路没有秘密
植物基础知识(十一):花的组成
《2024 Z世代双十一消费行为报告》:年轻人参与双十一“剁手”比例再提升
“十一”要赏什么花?
十一假期 花卉市场好去处
花店买十一朵玫瑰花多少钱
【十一花坛常见花卉】
【十一花坛常用花卉】
【上云拼团Go】如何在腾讯云双十一活动中省钱
网址: WPF中的binding(十一) https://www.huajiangbk.com/newsview793220.html
上一篇: 快=不家用?还真不一定! |
下一篇: Go语言全栈开发:结构体 |
推荐分享

- 1君子兰什么品种最名贵 十大名 4012
- 2世界上最名贵的10种兰花图片 3364
- 3花圈挽联怎么写? 3286
- 4迷信说家里不能放假花 家里摆 1878
- 5香山红叶什么时候红 1493
- 6花的意思,花的解释,花的拼音 1210
- 7教师节送什么花最合适 1167
- 8勿忘我花图片 1103
- 9橄榄枝的象征意义 1093
- 10洛阳的市花 1039