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

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

  1. class GetFileName : IValueConverter
  2. {
  3. //Convert方法用来将数据转换成我们想要的显示的格式
  4. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  5. {
  6. FileInfo fi = new FileInfo((string)value);
  7. return fi.Name;
  8. }
  9. //ConvertBack方法将显示值转换成原来的格式,因为我不需要反向转换,所以直接抛出个异常
  10. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  11. {
  12. throw new NotImplementedException();
  13. }
  14. }

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

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


为了使用的更方便,我们在Resources集合中创建一个转换器对象

  1. <Window.Resources>
  2. <local:GetFileName x:Key="GetFileName"></local:GetFileName>
  3. </Window.Resources>


现在我们去绑定数据的地方使用StaticResource来指向转换器
<TextBlock>

  1. <TextBlock.Text>
  2. <Binding Path="FileName">
  3. <Binding.Converter>
  4. <local:GetFileName></local:GetFileName>
  5. </Binding.Converter>
  6. </Binding>
  7. </TextBlock.Text>
  8. </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

 
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/linlf03/p/2135683.html