您的位置:首页 > 产品设计 > UI/UE

WPF 使用值转换器进行绑定数据的转换IValueConverter

2011-08-12 08:56 661 查看
有的时候,我们想让绑定的数据以其他的格式显示出来,或者转换成其他的类型,我们可以使用值转换器来实现.
比如我数据中保存了一个文件的路径”c:\abc\abc.exe”,但是我想让他在前台列表中显示为”abc.exe”.
首先我们先建一个IvalueConverter接口的类.

classGetFileName:IValueConverter

{

//Convert方法用来将数据转换成我们想要的显示的格式

publicobjectConvert(objectvalue,TypetargetType,objectparameter,CultureInfoculture)

{

FileInfofi=newFileInfo((string)value);

returnfi.Name;

}

//ConvertBack方法将显示值转换成原来的格式,因为我不需要反向转换,所以直接抛出个异常

publicobjectConvertBack(objectvalue,TypetargetType,objectparameter,CultureInfoculture)

{

thrownewNotImplementedException();

}

}

为了使用这个转换器,我们要将项目的名称空间映射到xaml中,比如我项目名字为自动更新,用local作为空间名称前缀

xmlns:local="clr-namespace:自动更新"

<Window.Resources> <local:GetFileNamex:Key="GetFileName"></local:GetFileName> </Window.Resources> <Window.Resources> <local:GetFileNamex:Key="GetFileName"></local:GetFileName> </Window.Resources>
现在我们去绑定数据的地方使用StaticResource来指向转换器
<TextBlock>

<TextBlock.Text>

<BindingPath="FileName">

<Binding.Converter>

<local:GetFileName></local:GetFileName>

</Binding.Converter>

</Binding>

</TextBlock.Text>

</TextBlock>

原文:http://blog.csdn.net/slzlren/article/details/6595905

Forexample:



namespaceOppositeValueConverterDemo
{
publicclassOppConverter:IValueConverter
{
#regionIValueConverter成员

objectIValueConverter.Convert(objectvalue,TypetargetType,objectparameter,System.Globalization.CultureInfoculture)
{
if(targetType!=typeof(bool))
{
thrownewInvalidOperationException("Thetargetmustbeaboolean");

}
return!(bool)value;
}

objectIValueConverter.ConvertBack(objectvalue,TypetargetType,objectparameter,System.Globalization.CultureInfoculture)
{
thrownewNotImplementedException();
}

#endregion
}
}


下面是XAML代码:

<Grid>
<Grid.Resources>
<wf:OppConverterx:Key="OppositeConverter"/>
</Grid.Resources>
<StackPanelMargin="10,10,10,10">
<RadioButtonx:Name="myRadio"IsChecked="True">Testconvert</RadioButton>
<RadioButtonHeight="20"Name="redYellow">Yellow</RadioButton>
<RadioButtonHeight="20"Name="redGreen"VerticalAlignment="Bottom">Green</RadioButton>
<TextBoxText="SampleText"IsEnabled="{BindingElementName=myRadio,Path=IsChecked,Converter={StaticResourceOppositeConverter}}"/>
</StackPanel>
</Grid>


效果如下图:当Testconvert选中时,TextBoxSampleText的InEnable=false









内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: