using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Data; namespace WPFComponents
{
[ValueConversion(typeof(string), typeof(int))]
public class StringToIntegerConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return System.Convert.ToInt32(value);
} public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return System.Convert.ToString(value);
}
}
}
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Data; namespace WPFComponents
{
[ValueConversion(typeof(string), typeof(string))]
public class StringToLowerCaseConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return System.Convert.ToString(value).ToLower();
} public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return System.Convert.ToString(value);
}
}
}
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Data;
using System.Xml; namespace WPFComponents
{
[ValueConversion(typeof(XmlElement), typeof(decimal))]
public class XmlElementToDecimalConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return System.Convert.ToDecimal(((XmlElement)value).InnerText);
} public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return System.Convert.ToString(value);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Globalization;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows;
using System.Windows.Controls; namespace WPFComponents
{
[ValueConversion(typeof(ListBoxItem), typeof(Thickness))]
public class IndexToMarginConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Thickness ret;
int itemIndex;
ListBoxItem lstItem;
ListBox lstBox; lstItem = (value as ListBoxItem);
lstBox = (ListBox)ItemsControl.ItemsControlFromItemContainer(lstItem);
itemIndex = lstBox.ItemContainerGenerator.IndexFromContainer(lstItem); if ((itemIndex % ) != )
ret = new Thickness(, , , );
else
ret = new Thickness(, , , ); return ret;
} public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Globalization;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows;
using System.Windows.Controls; namespace WPFComponents
{
[ValueConversion(typeof(ListBoxItem), typeof(decimal))]
public class IndexToAngleConverter : IValueConverter
{
public const int ANGLE = ; public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double ret;
int itemIndex;
ListBoxItem lstItem;
ListBox lstBox; // The 'value' parameter is the ListBoxItem
lstItem = (value as ListBoxItem);
// Get a reference to the list box so we can get the index of which item is being drawn
lstBox = (ListBox)ItemsControl.ItemsControlFromItemContainer(lstItem);
// Get the index of the item being drawn
itemIndex = lstBox.ItemContainerGenerator.IndexFromContainer(lstItem); if ((itemIndex % ) != )
ret = ANGLE;
else
ret = -(ANGLE); return ret;
} public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data; namespace Halliburton.Castor.Views.Converter
{
class DateToDayStringConverter : IValueConverter
{ public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{ DateTime? date = (DateTime?)value;
return date.HasValue ? date.Value.Day.ToString() : "";
} public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Data; namespace Halliburton.Castor.Views.Converter
{
class EnumMatchToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value == null || parameter == null)
return false; string checkValue = value.ToString();
string targetValue = parameter.ToString();
return checkValue.Equals(targetValue,
StringComparison.InvariantCultureIgnoreCase);
} public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value == null || parameter == null)
return null; bool useValue = (bool)value;
string targetValue = parameter.ToString();
if (useValue)
return Enum.Parse(targetType, targetValue); return null;
}
}
}
public class InverseBooleanConverter<bool> : ValueConverter
{
protected override bool Convert(bool value, Type targetType, object parameter, CultureInfo culture)
{
return !value;
} protected override bool ConvertBack(bool value, Type targetType, object parameter, CultureInfo culture)
{
return !value;
}
}
public class BoolToVisibilityConverter<bool,Visibility> : ValueConverter
{
protected override Visibility Convert(bool value, Type targetType, object parameter, CultureInfo culture)
{
return value ? Visibility.Visible : Visibility.Collapsed;
} protected override bool ConvertBack(Visibility value, Type targetType, object parameter, CultureInfo culture)
{
return value == Visibility.Visible;
}
}

Byte Array to Image Converter

ByteToImageConverter will convert byte array of image to a BitmapImage which can be used in Source property of an image. This can be used when we have an image saved in binary form in database and we want to bind that and show in image control. We can show a default image if byte array is null by uncommenting the code in “else” part of BitmapToImageConverter class.

 public class ByteToImageConverter : IValueConverter
{
public BitmapImage ConvertByteArrayToBitMapImage(byte[] imageByteArray)
{
BitmapImage img = new BitmapImage();
using (MemoryStream memStream = new MemoryStream(imageByteArray))
{
img.SetSource(memStream);
}
return img;
} public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
BitmapImage img = new BitmapImage();
if (value != null)
{
img = this.ConvertByteArrayToBitMapImage(value as byte[]);
}
else
{
//img = new BitmapImage(new Uri("/AssemblyName;component/Images/defaultImage.jpg", UriKind.Relative));
img = null;
}
return img;
} public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
<Image Margin="3" Source="{Binding Path=ByteArray, Converter={StaticResource byteToImageConverter}}"/>

Null or Empty Visibility Converter

NullEmptyVisibilityConverter can be used if we don’t want to show the control if value in binding is null. In above class, we are setting Visibility property as Collapsed if value is null or if string type value is null or empty.

public class NullEmptyVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
{
return Visibility.Collapsed;
}
else if (value.GetType() == typeof(string) && string.IsNullOrWhiteSpace(value.ToString()) == true)
{
return Visibility.Collapsed;
}
else
{
return Visibility.Visible;
}
} public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new Exception("Not implemented");
}
}
<TextBlock Margin="3" Text="{Binding Path=Data, Converter={StaticResource nullVisibilityConverter}}"/>

Negative Converter

Sometime we want to display reverse result of the binded value. For example, we want to disable the control if value is true. Now the disable control we have to set IsEnabled = false and we have value of true to disable. So in this case we can use above NegativeConverter.

In above example code,
we are unchecking the chkSecond checkbox if chkFirst checkbox is
checked and vice versa. So for this we are setting staticResource of
NegativeConverter in binding converter property

Public Class NegativeConverter
Implements IValueConverter
Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.Convert
If value.[GetType]() Is GetType(Boolean) Then
Dim result As Boolean = CBool(value)
Return Not result
Else
Return value
End If
End Function Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
Throw New Exception("Not implemented")
End Function
End Class
        <StackPanel Orientation="Vertical">
<CheckBox HorizontalAlignment="Left" Margin="3" Width="100" Height="25" Name="chkFirst"/>
<CheckBox Name="chkSecond" HorizontalAlignment="Left" Margin="3" Height="25" IsChecked="{Binding Path=IsChecked, ElementName=chkFirst, Converter={StaticResource negativeConverter}}"/>
</StackPanel>

Multiplication Converter

In the above code in txtSecond textbox we are binding  it’s width property to txtFirst textbox width property. So we have set ElementName as txtFirst and Path as ActualWidth. And we want to have txtSecond width double of txtFirst. So we would be setting staticresource of MultiplyConverter in converter property and “2.0” as ConverterParameter property.

Now in MultiplyConverter class we would have ActualWidth of txtFirst in
value parameter and “2.0” in “parameter” parameter. So we will multiply
the two value and return the result.

Public Class MultiplyConverter
Implements IValueConverter Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.Convert
If parameter IsNot Nothing Then
Dim result As Double = Double.Parse(parameter.ToString())
Return CDbl(value) * result
Else
Return CDbl(value)
End If
End Function Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
Throw New Exception("Not implemented")
End Function
 <StackPanel Orientation="Vertical">
<TextBox HorizontalAlignment="Left" Margin="3" Width="100" Height="25" Name="txtFirst"/>
<TextBox Name="txtSecond" HorizontalAlignment="Left" Margin="3" Height="25" Width="{Binding Path=ActualWidth, ElementName=txtFirst, Converter={StaticResource multiplyConverter}, ConverterParameter=2.0}"/>
</StackPanel>

Divide Converter

Similar to Multiplication Converter,  in the above code in txtSecond textbox we are binding  it’s width property to txtFirst textbox width property. So we have set ElementName as txtFirst and Path as ActualWidth. And we want to have txtSecond width half of txtFirst. So we would be setting staticresource of DivideConverter in converter property and “2.0” as ConverterParameter property.

Now in DivideConverter class we would have ActualWidth of txtFirst in
value parameter and “2.0” in “parameter” parameter. So we will divide
the ActualWidth by “2.0” and return the result.

Public Class DivideConverter
Implements IValueConverter Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.Convert
If parameter IsNot Nothing Then
Dim result As Double = Double.Parse(parameter.ToString()) If result > Then
Return CDbl(value) / result
Else
Return CDbl(value)
End If Else
Return CDbl(value)
End If
End Function Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
Throw New Exception("Not implemented")
End Function
End Class
 <StackPanel Orientation="Vertical">
<TextBox HorizontalAlignment="Left" Margin="3" Width="100" Height="25" Name="txtFirst"/>
<TextBox Name="txtSecond" HorizontalAlignment="Left" Margin="3" Height="25" Width="{Binding Path=ActualWidth, ElementName=txtFirst, Converter={StaticResource divideConverter}, ConverterParameter=2.0}"/>
</StackPanel>

Subtract Converter

Here we want txtSecond textbox, 15 pixels less than txtFirst.  In above code in txtSecond textbox we are binding  it’s width property to txtFirst textbox width property. So we have set ElementName as txtFirst and Path as ActualWidth. And as we want to have txtSecond 15 pixels less than txtFirst, we would be setting staticresource of SubtractConveter in converter property and “15.0” as ConverterParameter property.

Now in SubtractConverter class we would have ActualWidth of txtFirst in
value parameter and “15.0” in “parameter” parameter. So we will subtract
15 from  ActualWidth and return the result.

Public Class SubtractConverter
Implements IValueConverter Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.Convert
If parameter IsNot Nothing Then
Dim result As Double = Double.Parse(parameter.ToString())
Return CDbl(value) - result
Else
Return CDbl(value)
End If
End Function Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
Throw New Exception("Not implemented")
End Function
End Class
<StackPanel Orientation="Vertical">
<TextBox HorizontalAlignment="Left" Margin="3" Width="100" Height="25" Name="txtFirst"/>
<TextBox Name="txtSecond" HorizontalAlignment="Left" Margin="3" Height="25" Width="{Binding Path=ActualWidth, ElementName=txtFirst, Converter={StaticResource subtractConverter}, ConverterParameter=15.0}"/>
</StackPanel>

Common Converters in WPF/Silverlight的更多相关文章

  1. WPF/Silverlight HierarchicalDataTemplate 模版的使用(转)

    上一篇 对Wpf/Silverlight Template 进行了总结,本篇继续上一篇,主要是介绍 HierarchicalDataTemplate 的使用方法.HierarchicalDataTem ...

  2. XData -–无需开发、基于配置的数据库RESTful服务,可作为移动App和ExtJS、WPF/Silverlight、Ajax等应用的服务端

    XData -–无需开发.基于配置的数据库RESTful服务,可作为移动App和ExtJS.WPF/Silverlight.Ajax等应用的服务端   源起一个App项目,Web服务器就一台,已经装了 ...

  3. WPF/Silverlight Template使用及总结(转)

    WPF/Silverlight 中的控件都有Style和Template两种属性.前者解释为样式,是用来改变控件原有属性的,比如 Button 控件的(Width,Height,Background ...

  4. WPF/Silverlight Layout 系统概述——Arrange(转)

    Arrange过程概述 普通基类属性对Arrange过程的影响 我们知道Measure过程是在确定DesiredSize的大小,以便Arrange过程参考这个DesiredSize,确定给MyPane ...

  5. WPF/Silverlight Layout 系统概述——Measure(转)

    前言 在WPF/Silverlight当中,如果已经存在的Element无法满足你特殊的需求,你可能想自定义Element,那么就有可能会面临重写MeasureOverride和ArrangeOver ...

  6. Mvvm Light Toolkit for WPF/Silverlight系列之搭建mvvmlight开发框架

    Mvvm Light Toolkit for WPF/Silverlight系列之搭建mvvmlight开发框架   本章节,我将通过示例介绍如何搭建mvvmlight开发环境.示例中的我会针对wpf ...

  7. WPF/Silverlight深度解决方案:(一)解锁被Storyboard束缚的关联属性

    原文 WPF/Silverlight深度解决方案:(一)解锁被Storyboard束缚的关联属性 如果您在使用WPF/Silverlight进行相关动画开发中使用了Storyboard,并对关联属性进 ...

  8. WPF/Silverlight中图形的平移,缩放,旋转,倾斜变换演示

    原文:WPF/Silverlight中图形的平移,缩放,旋转,倾斜变换演示 为方便描述, 这里仅以正方形来做演示, 其他图形从略. 运行时效果图:XAML代码:// Transform.XAML< ...

  9. WPF/Silverlight中的RichTextBox总结

    WPF/Silverlight中的RichTextBox总结   在WPF或者是在Silverlight中有个非常强大的可以编辑的容器控件RichTextBox,有的时间会采取该控件来作为编辑控件.鉴 ...

随机推荐

  1. JBPM4入门——8.等待节点的分支执行

    JBPM入门系列文章: JBPM4入门——1.jbpm简要介绍 JBPM4入门——2.在eclipse中安装绘制jbpm流程图的插件 JBPM4入门——3.JBPM4开发环境的搭建 JBPM4入门—— ...

  2. C# winform 自定义控件

    近来因为项目的问题,开始研究winform自定义控件,这篇主要是将自定义控件的属性在属性编辑器中可编辑,如果你对自定义控件比较了解的,就不用继续往下看了 首先,我创建了一个类UserButton,继承 ...

  3. c/c++ 编译器内存对齐问题

    C语言结构体对齐问题详解 转载自:http://blog.csdn.net/tiany524/article/details/6295551 测试环境32位机 WinXP: 编译器VC6(MS cl. ...

  4. PHP开发规范

    十.开发规范下面我们讲解 Yii 编程中推荐的开发规范.为简单起见,我们假设 WebRoot 是 Yii 应用安装的目录.1.URL默认情况下,Yii 识别如下格式的 URL: http://host ...

  5. 把raw目录下的几张照片存放到SD卡里面去

    try { //SD卡路径 String filename =android.os.Environment .getExternalStorageDirectory().getAbsolutePath ...

  6. NewtonPrincipia_物体的运动_求向心力

    NewtonPrincipia_物体的运动_求向心力 让我们看一下十七世纪的被苹果砸中的艾萨克,是怎样推导出向心力公式的 在现在的观点看来,其中涉及到的很多没有符号表示的微分量.下面的内容只是叙述了推 ...

  7. 黑马程序员——Block数据类型

    Block数据类型,又被称为代码段.因为它可以封装一段代码.苹果官方建议多用block.因为在多线程控制.异步任务,集合遍历.集合排序.动画转场等方面用的很多. Block的特点: 1.Block 用 ...

  8. 如何开启php报错

    今天碰到一个很二的问题,安装了php网站之后,发现nginx一直无法解析到index.php文件,显示为空白,从后台的日志来看是500错误,但是同目录下的phpinfo.php却可以正常解析.想来应该 ...

  9. [cocos2d-js]按钮整合成大图后打APK后不显示

    网页版本都能正常显示碎图和整合成大图的 手机版本不正常 var btnKick = cc.MenuItemImage.create( "#btn_kick.png", " ...

  10. 轻松学习Linux之认识Shell

            Shell是一个命令解释器提供了用户与内核进行交互操作的一种接口shell,编程对於系统管理员或是一般使用者都相当有用,除了自动化,还可写出一些有趣的小工具,Linux本身有各种版本一 ...