Common Converters in WPF/Silverlight
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
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
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
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
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>
最新文章
- [C1] 实现 C1FlexGrid 撤销还原功能
- EMC学习之电磁辐射
- Configure LDAP Server(centos7 openldap)
- c查漏补缺
- 使用RBTool自动提交code review请求
- Python 学习之urllib模块---用于发送网络请求,获取数据(2)
- Topas命令详解
- TCP/IP 中文译名为传输控制协议/因特网互联协议,又叫网络通讯协议
- 线程 (detach的作用)
- 吐槽下CSDN编辑器
- .net DataTable 取值辅助类
- 基于visual Studio2013解决面试题之0701寻找丑数
- ubuntu文本界面乱码的中国解决方案
- JavaScript设计模式----装饰者模式
- 线程同步——用户模式下线程同步——Slim读写锁实现线程同步
- ios成长之每日一遍(day 3)
- [SublimeText] 之 Packages
- 小米范工具系列之十:小米范SSH批量命令执行工具
- 【322】python控制键盘鼠标:pynput
- Pycharm 2018.2.1-2018.1
热门文章
- Android 自定义RadioButton的样式
- LA 2995 Image Is Everything 立方体成像 World Final 2004
- grep -A -B选项详解和mysqlbinlog
- StringUtils判断字符串是否为空的方法
- 【NYOJ-187】快速查找素数—— 枚举法、筛选法、打表法
- jquery ajax jsonp跨域调用实例代码
- 什么是REST?以及RESTful的实现
- c++ 一个类使用另外一个类的变量或方法
- Linux makefile教程之书写命令四[转]
- poj 2185(二维kmp)