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. .Net dll多个同名的程序集版本冲突共存与通过基本代码或探测定位程序集方案

    .Net dll多个同名的程序集版本冲突共存与通过基本代码或探测定位程序集方案 在使用调用程序集的引用中的信息和配置文件中的信息确定了正确的程序集版本之后,并且在公共语言运行时在全局程序集缓存中进行检 ...

  2. (二)win7下用Intelij IDEA 远程调试spark standalone 集群

    关于这个spark的环境搭建了好久,踩了一堆坑,今天 环境: WIN7笔记本  spark 集群(4个虚拟机搭建的) Intelij IDEA15 scala-2.10.4 java-1.7.0 版本 ...

  3. Eclipse 打开编辑文件所在文件夹方法

    一个便捷的方法在eclipse的菜单中,依次点击Run->External Tools-> External Tools configurations添加一个新的工具 OpenContai ...

  4. mysql 表日常变化前几

    mysql 表日常变化前几use performance_schema create table test.snap1 as SELECT OBJECT_SCHEMA, OBJECT_NAME, CO ...

  5. 【转】uboot移植(一)BootLoader基本概念

    原文网址:http://blog.chinaunix.net/uid-25445243-id-3869348.html 一.BootLoader简介1.1.嵌入式Linux软件结构与分布 在一般情况下 ...

  6. ArcEngine 通过SpatialRelDescription删除不相交要素

    ISpatialFilter.SpatialRel设置为esriSpatialRelRelate,并且设置SpatialRelDescription为某个字符串.该字符串的构造方法:该字符串为长度为9 ...

  7. XAMPP 的安装配置

    --转载时请保留下面,以供大家加我MSN,增强交流,共同学习.--姜庭华  msn: jaimejth@live.cn--博客:http://blog.csdn.net/jaimejth 软件下载在以 ...

  8. Effective java笔记8--序列化

    对象的序列化(object serialization)API,它提供了一个框架,用来将对象编码成一个字节流,以及从字节流编码中重新构建对象. 一.谨慎地实现Serializable     要想使一 ...

  9. 实测 windows下nginx很不稳定,换成squid好多了

    在windows server 2003 下尝试了号称支持50,000个并发连接数响应的nginx,结果相当不理想. 具体表现为时不时网页就卡住不动了,需要再刷新一次网页才能显示,而服务器cpu和内存 ...

  10. CSS学习进度备忘

    书签:“CSS 高级”跳过:另外跳过的内容有待跟进 __________________ 学习资源:W3School. _________________ 跳过的内容:1.“CSS id 选择器”的“ ...