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. 【英语】Bingo口语笔记(61) - mind系列

  2. TCP握手

    1.TCP的三次握手四次挥手 第一次握手:Client将标志位SYN置为1,随机产生一个值seq=J,并将该数据包发送给Server,Client进入SYN_SENT状态,等待Server确认. 第二 ...

  3. 2016第20周四java基础概念

    简单的说JDK=JRE+Java编译器.调试器.工具类库等:JRE=JVM(类似于jre目录下的bin)+必要运行的类库(类似于jre目录下的lib) JVM:Java Virtual Mechina ...

  4. 【模版消息】C#推送微信模版消息(Senparc.Weixin.MP.dll)

    定义的模版内容: {{first.DATA}} 商品名称:{{product.DATA}} 商品价格:{{price.DATA}} 购买时间:{{time.DATA}} {{remark.DATA}} ...

  5. PHP遍历数组

    foreach PHP代码: <?php   $url = array( '新浪' =>'www.sina.com' ,                    '雅虎' =>'www ...

  6. RESTful HTTP的实践

    REST是一种风格,而不是标准.因为既没有REST RFC,也没有REST协议规范或者类似的规定.REST架构是Roy Fielding(他也是HTTP和URI规范的主要作者之一)在一篇论文中描述的. ...

  7. kinect 录制彩色和深度视频

    安装 KinectSDK-v1.8-Setup.exe OpenNI-Windows-x86-2.1.0.msi Qt工程 拷贝 Redist 下内容到 编译的exe所在目录 #include < ...

  8. 部署测试环境(ubuntu+mysql+tomcat)

    背景:入职新公司,广州这边没有测试开发环境,需要自己搭建一个:要求ubuntu+mysql+tomcat有具体版本要求:   2015/4/13 下载Ubuntu12.04 http://mirror ...

  9. EFSQLserver

    1.增加一条烽据 FLYNEWQKEntities dataContext = new FLYNEWQKEntities(); Log log = new Log(); log.Data1 = &qu ...

  10. Windows 下命令行修改文件夹的控制权限 Cacls

    设置用户访问权限:我们经常要修改目录和文件的访问权限,使用Cacls命令就很容易做到.下面要赋予本机用户testuser对d盘下 test目录及其所有子目录中的文件有完全控制权限.在命令提示符对话框中 ...