×
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)
m (Influencer - - BooleanToVisibilityConverter)
Line 51: Line 51:
 
<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.
Line 77: Line 77:
 
   }
 
   }
 
</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.

Revision as of 23:50, 27 October 2012

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 (27 Oct 2012)

Contents

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

  • data type conversions, e.g. BooleanToVisibilityConverter
  • operations on bound data, e.g. BooleanNegationConverter
  • 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 the converters is given in the same article.

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 these converters can be used for Windows 8.

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;
}
}

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;
}
}

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();
}
}

DatabindingDebugConverter

This converter is described in the [How to debug data binding problems on Windows Phone] article.

/// <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;
}
}

Invitation

Please feel free to add further value converter samples!

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 BooleanToVisibilityConverter is used to control the visibility of the clock with a ToggleSwitch.

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]]

730 page views in the last 30 days.