Coding4Fun的4个 ValueConverter 示例
来源:互联网 发布:淘宝dsr评分计算器 编辑:程序博客网 时间:2024/06/05 20:06
Talking about Converters in WP7 | Coding4fun toolkit converters in depth
published on: 2/3/2011 | Views: 24576Currently rated 4.00 by 2 people
by WindowsPhoneGeek
In this post I am going to talk about value converters in Silverlight for Windows Phone 7 and mainly about theCoding4fun Toolkit converters in depth. I will explain everything you need to know about them, sample usage, implementation etc.
Silverlight data binding engine allows data to be bound through XAML or programmatically with code. Sometimes you want to databind two properties that have incompatible types. You need some code that converts the value from source to target type and back. This code is called ValueConverter.
Basically a Value Converter is a class, that implements the interface IValueConverter
interface.This interface exposes two methods: object Convert(object value)
and ConvertBack(object value).
The binding engine calls the Convert and ConvertBack methods if the Converter parameter is defined for the binding. When data is passed from the source, the binding engine calls Convert and passes the returned data to the target. When data is passed from the target, the binding engine calls ConvertBack and passes the returned data to the source. The following example shows how to set the Converter parameter.
Coding4fun Converters
Coding4fun toolkit gives us some very helpful converters which you can use in your application even without writing any custom code.
To begin using these converters first add a reference to the Coding4Fun.Phone.Controls.dll assembly.
Just create a new folder in your project and add the assembly there, after that add it as a reference to your project.
NOTE: You have to download and rebuild the Coding4Fun Toolkit project in order to generate the assembly. You can getCoding4Fun.Phone.Controls.Toolkit.dll from the the following folder:
\coding4fun-61253\Coding4Fun.Phone\Coding4Fun.Phone.Controls\Bin\Debug
the next step is to add the "controls" prefix declaration. Make sure that your page declaration includes the "controls" namespace:
xmlns:c4fControls="clr-namespace:Coding4Fun.Phone.Controls.Converters;assembly=Coding4Fun.Phone.Controls"
Sample Usage
At first we will add some light/dark images to the project and will define instances of all converters in Resources of MainPage.xaml. The source code is as follows:
<phone:PhoneApplicationPage.Resources> <c4fControls:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/> <c4fControls:VisibilityToBooleanConverter x:Key="VisibilityToBooleanConverter"/> <c4fControls:ThemedImageConverter x:Key="ThemedImageConverter"/> <c4fControls:ThemedInverseImageConverter x:Key="ThemedInverseImageConverter"/></phone:PhoneApplicationPage.Resources>
- BooleanToVisibilityConverter
Use the BooleanToVisibilityConverter class to convert a Boolean to and from a Visibility value.
Example:
<CheckBox x:Name="checkBox"/><TextBlock Text="CheckBox is Checked" Visibility="{Binding ElementName=checkBox, Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}}"/>
- StringToVisibilityConverter
Converts a string to Visibility.
- ThemedImageConverter
This converter is an Image converter.
Example:
<Button> <Image Stretch="None" Source="{Binding Converter={StaticResource themedImageConverter}, ConverterParameter={StaticResource PhoneBackgroundColor}}"DataContext="/WP7SampleProject4;component/Images/{0}/appbar.feature.camera.rest.png" /></Button>
- ThemedInverseImageConverter
This converter is almost the same as ThemedImageConverter but it inverses the image.
Example:
<Button Background="YellowGreen"> <Image Stretch="None" Source="{Binding Converter={StaticResource ThemedInverseImageConverter}, ConverterParameter={StaticResource PhoneBackgroundColor}}" DataContext="/WP7SampleProject4;component/Images/{0}/appbar.feature.camera.rest.png" /></Button>
- VisibilityToBooleanConverter
Represents the converter that converts Visibility enumeration values to and from Boolean values.
Example:
<CheckBox x:Name="checkBox1" IsChecked="{Binding ElementName=text, Path=Visibility, Converter={StaticResource VisibilityToBooleanConverter}}"/><ToggleButton x:Name="togglebutton" Content="Check/Uncheck CheckBox" /><TextBlock x:Name="text" Text="ToggleButton Pressed -> text is Visible" Visibility="{Binding ElementName=togglebutton, Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}}"/>
Coding4fun Converters Source Code Explained
NOTE: You do no need to write/use the below code in order to use the converter. You need to understand the code only if you need to modify or extend the converters!
- BooleanToVisibilityConverter
Source Code Explained:
The Convert method returns Visibility.Visible when true is passed in or Visibility.Collapsed when false is passed in. Note that the Visibility.Collapsed value hides the control and does not reserve space for it in a layout. When you call the ConvertBack method and specify a reference to an object, it returns true if the object is Visible; otherwise, it returns false.
public class BooleanToVisibilityConverter : IValueConverter{ public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return System.Convert.ToBoolean(value) ? Visibility.Visible : Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value.Equals(Visibility.Visible); }}
- ThemedImageConverter
Source Code Explained:
The Convert method at first identifies the current theme using
var isDarkTheme = (Application.Current.Resources.Contains("PhoneDarkThemeVisibility") && ((Visibility)Application.Current.Resources["PhoneDarkThemeVisibility"]) == Visibility.Visible);
After we have identified the theme we can create a full path to the image file by combining the value from the "value" parameter and either the "dark" or "light " folder names. Of coerce there is a check if we have already cached the image.
public class ThemedImageConverter : IValueConverter{ private static readonly Dictionary<String, BitmapImage> ImageCache = new Dictionary<string, BitmapImage>(); public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var isDarkTheme = (Application.Current.Resources.Contains("PhoneDarkThemeVisibility") && ((Visibility)Application.Current.Resources["PhoneDarkThemeVisibility"]) == Visibility.Visible); BitmapImage result = null; var str = value as string; // Path to the icon image if (str != null) { // Path to the icon image var path = string.Format(str, isDarkTheme ? "dark" : "light"); // Check if we already cached the image if (!ImageCache.TryGetValue(path, out result)) { result = new BitmapImage(new Uri(path, UriKind.Relative)); ImageCache.Add(path, result); } } return result; } ...}
- ThemedInverseImageConverter
Source Code Explained:
This converter is almost the same as ThemedImageConverter but it inverses the image.
var path = string.Format(str, isDarkTheme ? "light" : "dark")
- VisibilityToBooleanConverter
Source Code Explained:
Represents the converter that converts Visibility enumeration values to and from Boolean values.
public class VisibilityToBooleanConverter : IValueConverter{ private readonly BooleanToVisibilityConverter _boolToVis = new BooleanToVisibilityConverter(); public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return _boolToVis.ConvertBack(value, targetType, parameter, culture); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return _boolToVis.Convert(value, targetType, parameter, culture); }}
Here is one more set of converters by Nigel Sampson that you may find helpful: Useful Value Converters
That was all about the Converters from the Coding4fun Toolkit in depth. You can find the full source code here:
I hope that the article was helpful.
- Coding4Fun的4个 ValueConverter 示例
- Coding4Fun:儿童的编程语言
- Coding4Fun:儿童的编程语言
- Coding4Fun: 一个简单的 RSS 源
- Coding4Fun.Controls的ToastPrompt小用
- <wp7>另类弹窗,coding4Fun插件提供的弹窗
- WP7开发中Coding4Fun的五种弹出框介绍
- WPF Binding值转换器ValueConverter
- Coding4Fun:KPL:Pong!
- Coding4Fun:开始游戏开发
- Coding4Fun:开始游戏开发
- coding4fun:集成聚合内容
- Coding4Fun Kinect Toolkit
- Studio 2005 的 101 个示例 --MSDN
- Visual Studio 2005 的 101 个示例
- 打造第一个Spring AOP的示例
- Visual Studio 2005 的 101 个示例
- 2个ASP.NET Ajax 的示例
- 玩转Web之JavaScript(二)-----javaScript语法总结(二) 涉及Date与数组的语法
- 黑马程序员----IO流
- 利用npoi导出excel
- Android 4.0 截屏(Screenshot)代码流程小结
- android Socket使用笔记
- Coding4Fun的4个 ValueConverter 示例
- 设计模式(13) 对象行为型模式和职责链模式
- android背景选择器selector使用方法
- 12:00 a.m.究竟是中午12点还是午夜12点?
- cocos2d-x3.0+VS2013环境配置
- VC++字符串截取总结
- 使用 Eclipse 远程调试 Java 应用程序
- java和C#中静态字段和静态方法的使用异同
- javascript性能提升——脚本合并