有的时候,我们想让绑定的数据以其他的格式显示出来,或者转换成其他的类型,我们可以使用值转换器来实现.
比如我数据中保存了一个文件的路径”c:\abc\abc.exe”,但是我想让他在前台列表中显示为”abc.exe”.
首先我们先建一个IvalueConverter接口的类.
- class GetFileName : IValueConverter
- {
- //Convert方法用来将数据转换成我们想要的显示的格式
- public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
- {
- FileInfo fi = new FileInfo((string)value);
- return fi.Name;
- }
- //ConvertBack方法将显示值转换成原来的格式,因为我不需要反向转换,所以直接抛出个异常
- public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
- {
- throw new NotImplementedException();
- }
- }
为了使用这个转换器,我们要将项目的名称空间映射到xaml中,比如我项目名字为自动更新,用local作为空间名称前缀
xmlns:local="clr-namespace:自动更新"
为了使用的更方便,我们在Resources集合中创建一个转换器对象
- <Window.Resources>
- <local:GetFileName x:Key="GetFileName"></local:GetFileName>
- </Window.Resources>
现在我们去绑定数据的地方使用StaticResource来指向转换器
<TextBlock>
- <TextBlock.Text>
- <Binding Path="FileName">
- <Binding.Converter>
- <local:GetFileName></local:GetFileName>
- </Binding.Converter>
- </Binding>
- </TextBlock.Text>
- </TextBlock>
原文:http://blog.csdn.net/slzlren/article/details/6595905
For example:
|
namespace
OppositeValueConverterDemo
{
public
class
OppConverter : IValueConverter
{
#region IValueConverter 成员
object
IValueConverter.Convert(
object
value, Type targetType,
object
parameter, System.Globalization.CultureInfo culture)
{
if
(targetType !=
typeof
(
bool
))
{
throw
new
InvalidOperationException(
"The target must be a boolean"
);
}
return
!(
bool
)value;
}
object
IValueConverter.ConvertBack(
object
value, Type targetType,
object
parameter, System.Globalization.CultureInfo culture)
{
throw
new
NotImplementedException();
}
#endregion
}
}
|
下面是XAML代码:
|
<Grid>
<Grid.Resources>
<wf:OppConverter x:Key=
"OppositeConverter"
/>
</Grid.Resources>
<StackPanel Margin=
"10,10,10,10"
>
<RadioButton x:Name=
"myRadio"
IsChecked=
"True"
>Test convert</RadioButton>
<RadioButton Height=
"20"
Name=
"redYellow"
>Yellow</RadioButton>
<RadioButton Height=
"20"
Name=
"redGreen"
VerticalAlignment=
"Bottom"
>Green</RadioButton>
<TextBox Text=
"Sample Text"
IsEnabled=
"{Binding ElementName=myRadio, Path=IsChecked, Converter={StaticResource OppositeConverter}}"
/>
</StackPanel>
</Grid>
|
效果如下图:当Test convert选中时,TextBox Sample Text的InEnable=false
|
本文转自Work Hard Work Smart博客园博客,原文链接:http://www.cnblogs.com/linlf03/archive/2011/08/12/2135683.html,如需转载请自行联系原作者
|