×
Namespaces

Variants
Actions
(Difference between revisions)

Collection of Value converters for Windows Phone apps

From Nokia Developer Wiki
Jump to: navigation, search
influencer (Talk | contribs)
m (Influencer -)
influencer (Talk | contribs)
(Influencer -)
 
(19 intermediate revisions by 5 users not shown)
Line 1: Line 1:
[[Category:Windows Phone]][[Category:Silverlight]][[Category:Data Binding]][[Category:Code Examples]][[Category:UI]][[Category:Files/Data]]
+
[[Category:Files/Data on Windows Phone]][[Category:UI on Windows Phone]][[Category:Windows Phone 7.5]][[Category:Code Examples]][[Category:XAML]][[Category:Windows Phone 8]]
 
{{Abstract|This article gives some examples for value converters that can be used in different scenarios in Windows Phone apps}}
 
{{Abstract|This article gives some examples for value converters that can be used in different scenarios in Windows Phone apps}}
  
Line 9: Line 9:
 
|platform= <!-- Compatible platforms - e.g. Symbian^1 and later, Qt 4.6 and later -->
 
|platform= <!-- Compatible platforms - e.g. Symbian^1 and later, Qt 4.6 and later -->
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->  
+
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
|signing=<!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
+
|signing= <!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
 
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
 
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
 
|keywords= <!-- APIs, classes and methods (e.g. QSystemScreenSaver, QList, CBase -->
 
|keywords= <!-- APIs, classes and methods (e.g. QSystemScreenSaver, QList, CBase -->
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|translated-by= <!-- [[User:XXXX]] -->
 
|translated-by= <!-- [[User:XXXX]] -->
|translated-from-title= <!-- Title only -->  
+
|translated-from-title= <!-- Title only -->
 
|translated-from-id= <!-- Id of translated revision -->
 
|translated-from-id= <!-- Id of translated revision -->
|review-by=<!-- After re-review: [[User:username]] -->
+
|review-by= <!-- After re-review: [[User:username]] -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|update-by= <!-- After significant update: [[User:username]]-->
 
|update-by= <!-- After significant update: [[User:username]]-->
Line 26: Line 26:
  
 
== Introduction ==
 
== Introduction ==
Value converters are a versatile instrument helping in data binding scenarios on the Windows Phone (and Windows 8 Modern UI or WPF) platforms. The spectrum includes
+
Value converters ([http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx IValueConverter Interface]) are a versatile instrument helping in data binding scenarios on the Windows Phone (and Windows 8 Modern UI or WPF) platforms. The spectrum includes
  
 
* data type conversions, e.g. {{Icode|BooleanToVisibilityConverter}}
 
* data type conversions, e.g. {{Icode|BooleanToVisibilityConverter}}
 
* operations on bound data, e.g. {{Icode|BooleanNegationConverter}}
 
* operations on bound data, e.g. {{Icode|BooleanNegationConverter}}
 +
* individual text conversions, e.g. {{Icode|TimeToStringConverter}}
 
* special effects, like drawing dynamic images, e.g. {{Icode|TimeToShapeConverter}}
 
* special effects, like drawing dynamic images, e.g. {{Icode|TimeToShapeConverter}}
* debugging purposes, e.g.{{Icode| DatabindingDebugConverter}} see [[http://www.developer.nokia.com/Community/Wiki/How_to_debug_data_binding_problems_on_Windows_Phone How to debug data binding problems on Windows Phone]]
+
* debugging purposes, e.g.{{Icode| DatabindingDebugConverter}} see [[How to debug data binding problems on Windows Phone]]
  
  
An introduction into the necessary steps to use the converters is given in the same article.
+
An introduction into the necessary steps to use converters is given in [[How to debug data binding problems on Windows Phone]], too.
  
[[file: ConverterScreen.png]]
+
Another very interesting idea is a value converter whose conversion functions can be generated by script: [http://www.codeproject.com/Articles/29621/The-Last-IValueConverter The Last IValueConverter].
 +
 
 +
Here's a screenshot of how the sample app looks like:
 +
 
 +
[[file: ConverterScreen.png|300px]]
  
 
{{Note|The [http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx IValueConverter interface] is defined with different function parameters in Win 8 Modern UI aka "Metro" aka Windows 8 Store Apps. That's the reason I couldn't use a [http://msdn.microsoft.com/en-us/library/gg597391.aspx Portable Class Library] to contain the converter classes.
 
{{Note|The [http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx IValueConverter interface] is defined with different function parameters in Win 8 Modern UI aka "Metro" aka Windows 8 Store Apps. That's the reason I couldn't use a [http://msdn.microsoft.com/en-us/library/gg597391.aspx Portable Class Library] to contain the converter classes.
This also means that by changing the last two function parameters these converters can be used for Windows 8.}}
+
This also means that by changing the last two function parameters in the Convert and ConvertBack functions these converters can be used for Windows 8, too.}}
  
 
== BooleanToVisibilityConverter ==
 
== BooleanToVisibilityConverter ==
Line 49: Line 54:
 
For the first case the data binding syntax for the Visibility property refers to the IsChecked property of the controlling xaml element and includes the converter:
 
For the first case the data binding syntax for the Visibility property refers to the IsChecked property of the controlling xaml element and includes the converter:
 
<code xml>
 
<code xml>
<toolkit:ToggleSwitch Name="tgVis" Content="Clock Visible" IsChecked="True" Checked="ToggleSwitch_Checked" Unchecked="ToggleSwitch_Checked"/>
+
<toolkit:ToggleSwitch Name="tgVis" Content="Clock Visible" IsChecked="True"  
 +
  Checked="ToggleSwitch_Checked" Unchecked="ToggleSwitch_Checked"/>
 
<Path Data="{Binding CurrentTime, Converter={StaticResource TimeToShapeConverter}}"
 
<Path Data="{Binding CurrentTime, Converter={StaticResource TimeToShapeConverter}}"
  Stroke="White" Stretch="Uniform"
+
   Visibility="{Binding IsChecked, ElementName=tgVis,Converter={StaticResource BooleanToVisibilityConverter}}"
   Visibility="{Binding IsChecked, ElementName=tgVis,Converter={StaticResource BooleanToVisibilityConverter}}"/>
+
  Stroke="Gray" StrokeThickness="12" StrokeEndLineCap="Round" StrokeStartLineCap="Round"
 +
  Stretch="Uniform" Margin="6"/>
 
</code>
 
</code>
 
In the second case the usage is pretty standard data binding.
 
In the second case the usage is pretty standard data binding.
 
<code xml>
 
<code xml>
<Textblock Text="Make me invisible" Visibility="{Binding VisibilityProperty,Converter={StaticResource BooleanToVisibilityConverter}}"/></code>
+
<Textblock Text="Make me invisible"
 +
  Visibility="{Binding VisibilityProperty,Converter={StaticResource BooleanToVisibilityConverter}}"/>
 +
</code>
  
 
Here's the simple code for the converter:
 
Here's the simple code for the converter:
Line 77: Line 86:
 
   }
 
   }
 
</code>
 
</code>
 +
 
== BooleanNegationConverter  ==
 
== BooleanNegationConverter  ==
 
This one can be used to invert a boolean value, e.g. if a bool value and its negative are both needed.
 
This one can be used to invert a boolean value, e.g. if a bool value and its negative are both needed.
Line 162: Line 172:
 
   }
 
   }
 
</code>
 
</code>
 +
Regarding the usage in xaml see the above sample for {{Icode|BooleanToVisibilityConverter}}.
 +
 
== DatabindingDebugConverter ==
 
== DatabindingDebugConverter ==
This converter is described in the [[http://www.developer.nokia.com/Community/Wiki/How_to_debug_data_binding_problems_on_Windows_Phone How to debug data binding problems on Windows Phone]] article.
+
This converter is described in the [[How to debug data binding problems on Windows Phone]] article, which explains how to inspect elements before they are due to be displayed by a control.
 
<code csharp>
 
<code csharp>
 
/// <summary>
 
/// <summary>
Line 181: Line 193:
 
   }
 
   }
 
</code>
 
</code>
 +
 +
== Defining the Resources ==
 +
The following declaration tells the XAML page how to find the converters:
 +
<code csharp>
 +
  <phone:PhoneApplicationPage.Resources>
 +
      <local:TimeToStringConverter x:Key="TimeToStringConverter"/>
 +
      <local:TimeToShapeConverter x:Key="TimeToShapeConverter"/>
 +
      <local:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
 +
      <local:BooleanNegationConverter x:Key="BooleanNegationConverter"/>
 +
  </phone:PhoneApplicationPage.Resources>
 +
</code>
 +
 
== Invitation ==
 
== Invitation ==
 
Please feel free to add further value converter samples!
 
Please feel free to add further value converter samples!
  
 +
[[Category:Windows Phone 7.5]]
 
== Sample code ==
 
== Sample code ==
This article is accompagnied by a [[Media: ValueConverterSample.zip]] that just uses the two time converters to show the current time as a string and as an analog clock. The {{Icode|BooleanToVisibilityConverter}} is used to control the visibility of the clock with a ToggleSwitch.
+
This article is accompagnied by a [[Media:ValueConverterSample.zip|sample]] that just uses the two time converters to show the current time as a string and as an analog clock. The {{Icode|BooleanToVisibilityConverter}} is used to control the visibility of the clock with a {{Icode|ToggleSwitch}}. In order to use the {{Icode|ToggleSwitch}} you'll need the [http://phone.codeplex.com/ Windows Phone Toolkit].
  
 
{{VersionHint|Versions will be visible from this template when viewed in preview. You can delete this or leave it in the page as it is not displayed in final version}}
 
{{VersionHint|Versions will be visible from this template when viewed in preview. You can delete this or leave it in the page as it is not displayed in final version}}

Latest revision as of 00:07, 10 September 2013

This article gives some examples for value converters that can be used in different scenarios in Windows Phone apps

WP Metro Icon File.png
WP Metro Icon UI.png
SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
Code ExampleCompatibilityArticle
Created: influencer (26 Oct 2012)
Last edited: influencer (10 Sep 2013)

Contents

[edit] Introduction

Value converters (IValueConverter Interface) are a versatile instrument helping in data binding scenarios on the Windows Phone (and Windows 8 Modern UI or WPF) platforms. The spectrum includes

  • data type conversions, e.g. BooleanToVisibilityConverter
  • operations on bound data, e.g. BooleanNegationConverter
  • individual text conversions, e.g. TimeToStringConverter
  • special effects, like drawing dynamic images, e.g. TimeToShapeConverter
  • debugging purposes, e.g. DatabindingDebugConverter see How to debug data binding problems on Windows Phone


An introduction into the necessary steps to use converters is given in How to debug data binding problems on Windows Phone, too.

Another very interesting idea is a value converter whose conversion functions can be generated by script: The Last IValueConverter.

Here's a screenshot of how the sample app looks like:

ConverterScreen.png

Note.pngNote: The IValueConverter interface is defined with different function parameters in Win 8 Modern UI aka "Metro" aka Windows 8 Store Apps. That's the reason I couldn't use a Portable Class Library to contain the converter classes. This also means that by changing the last two function parameters in the Convert and ConvertBack functions these converters can be used for Windows 8, too.

[edit] BooleanToVisibilityConverter

This converter can translate a boolean value to the value type needed by the Visibility property of most XAML element. It's mostly used in two cases:

  • when a Checkbox or ToggleButton element interactively controls the visibility of another element
  • or when a background data value does the same.


For the first case the data binding syntax for the Visibility property refers to the IsChecked property of the controlling xaml element and includes the converter:

<toolkit:ToggleSwitch Name="tgVis" Content="Clock Visible" IsChecked="True" 
Checked="ToggleSwitch_Checked" Unchecked="ToggleSwitch_Checked"/>
<Path Data="{Binding CurrentTime, Converter={StaticResource TimeToShapeConverter}}"
Visibility="{Binding IsChecked, ElementName=tgVis,Converter={StaticResource BooleanToVisibilityConverter}}"
Stroke="Gray" StrokeThickness="12" StrokeEndLineCap="Round" StrokeStartLineCap="Round"
Stretch="Uniform" Margin="6"/>

In the second case the usage is pretty standard data binding.

<Textblock Text="Make me invisible"
Visibility="{Binding VisibilityProperty,Converter={StaticResource BooleanToVisibilityConverter}}"/>

Here's the simple code for the converter:

/// <summary>
/// Value converter that translates true to <see cref="Visibility.Visible"/> and false to
/// <see cref="Visibility.Collapsed"/>.
/// </summary>
public sealed class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return (value is bool && (bool)value) ? Visibility.Visible : Visibility.Collapsed;
}
 
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return value is Visibility && (Visibility)value == Visibility.Visible;
}
}

[edit] BooleanNegationConverter

This one can be used to invert a boolean value, e.g. if a bool value and its negative are both needed.

/// <summary>
/// Value converter that translates true to false and vice versa.
/// </summary>
public sealed class BooleanNegationConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return !(value is bool && (bool)value);
}
 
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return !(value is bool && (bool)value);
}
}

In this code fragment the converter is used to show the result of toggling the switch:

  <StackPanel Orientation="Horizontal">
<TextBlock Text="Toggle to switch to "/>
<TextBlock Text="{Binding IsChecked, ElementName=tgVis,Converter={StaticResource BooleanNegationConverter}}"/>
</StackPanel>
</code
== TimeToStringConverter ==
Display a date or time from a DateTime instance to displayable string using the TimeToStringConverter.
<code csharp>
/// <summary>
/// Value converter that converts a DateTime to a text and vice versa.
/// </summary>
public sealed class TimeToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
DateTime dt = (DateTime)value;
return dt.ToString();
}
 
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
DateTime dt;
DateTime.TryParse(value.ToString(), out dt);
return dt;
}
}

[edit] TimeToShapeConverter

Converts the time to a clock image using geometric shape objects. This a very rudimentary implementation but I think you get the idea what you can do...

/// <summary>
/// Value converter that creates a clock image from a time value.
/// Reference the System.Windows.Media namespace.
/// You can bind the result to a Path element.
/// </summary>
public sealed class TimeToShapeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
DateTime dt = (DateTime)value;
GeometryGroup coll = new GeometryGroup();
EllipseGeometry ell = new EllipseGeometry();
ell.Center = new Point(55, 55);
ell.RadiusX = ell.RadiusY = 60;
coll.Children.Add(ell);
LineGeometry hour = new LineGeometry();
double deg = (dt.Hour % 12) * Math.PI / 6;
hour.StartPoint = ell.Center;
hour.EndPoint = new Point(55 + Math.Sin(deg) * 35, 55 - Math.Cos(deg) * 35);
coll.Children.Add(hour);
LineGeometry minute = new LineGeometry();
minute.StartPoint = ell.Center;
deg = dt.Minute * Math.PI / 30;
minute.EndPoint = new Point(55 + Math.Sin(deg) * 50, 55 - Math.Cos(deg) * 50);
coll.Children.Add(minute);
return coll;
}
 
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}

Regarding the usage in xaml see the above sample for BooleanToVisibilityConverter.

[edit] DatabindingDebugConverter

This converter is described in the How to debug data binding problems on Windows Phone article, which explains how to inspect elements before they are due to be displayed by a control.

/// <summary>
/// Value Converter that does nothing except giving the chance to set a breakpoint.
/// </summary>
public sealed class DatabindingDebugConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return value;
}
 
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return value;
}
}

[edit] Defining the Resources

The following declaration tells the XAML page how to find the converters:

   <phone:PhoneApplicationPage.Resources>
<local:TimeToStringConverter x:Key="TimeToStringConverter"/>
<local:TimeToShapeConverter x:Key="TimeToShapeConverter"/>
<local:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
<local:BooleanNegationConverter x:Key="BooleanNegationConverter"/>
</phone:PhoneApplicationPage.Resources>

[edit] Invitation

Please feel free to add further value converter samples!

[edit] Sample code

This article is accompagnied by a sample that just uses the two time converters to show the current time as a string and as an analog clock. The BooleanToVisibilityConverter is used to control the visibility of the clock with a ToggleSwitch. In order to use the ToggleSwitch you'll need the Windows Phone Toolkit.

[edit] Version Hint

Windows Phone: [[Category:Windows Phone]]
[[Category:Windows Phone 7.5]]
[[Category:Windows Phone 8]]

Nokia Asha: [[Category:Nokia Asha]]
[[Category:Nokia Asha Platform 1.0]]

Series 40: [[Category:Series 40]]
[[Category:Series 40 1st Edition]] [[Category:Series 40 2nd Edition]]
[[Category:Series 40 3rd Edition (initial release)]] [[Category:Series 40 3rd Edition FP1]] [[Category:Series 40 3rd Edition FP2]]
[[Category:Series 40 5th Edition (initial release)]] [[Category:Series 40 5th Edition FP1]]
[[Category:Series 40 6th Edition (initial release)]] [[Category:Series 40 6th Edition FP1]] [[Category:Series 40 Developer Platform 1.0]] [[Category:Series 40 Developer Platform 1.1]] [[Category:Series 40 Developer Platform 2.0]]

Symbian: [[Category:Symbian]]
[[Category:S60 1st Edition]] [[Category:S60 2nd Edition (initial release)]] [[Category:S60 2nd Edition FP1]] [[Category:S60 2nd Edition FP2]] [[Category:S60 2nd Edition FP3]]
[[Category:S60 3rd Edition (initial release)]] [[Category:S60 3rd Edition FP1]] [[Category:S60 3rd Edition FP2]]
[[Category:S60 5th Edition]]
[[Category:Symbian^3]] [[Category:Symbian Anna]] [[Category:Nokia Belle]]

This page was last modified on 10 September 2013, at 00:07.
702 page views in the last 30 days.