Converters implement the IValueConverter interface that defines two methods:
In other words:
Declare a converter:
xmlns:common="using:WBS.MyApp.Common"
...
<common:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
If there is an error in the conversion, do not throw an exception. Instead, return DependencyProperty.UnsetValue, which will stop the data transfer.
MSDN: DependencyProperty.UnsetValue specifies a static value that is used by the property system rather than null to indicate that the property exists, but does not have its value set.
Avoid using converters with the items of ListControls. Put conversions as an additional property in ViewModel instead.
Example: BooleanToGridLengthConverter
public sealed class BooleanToGridLengthConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { GridLength lenZero = new GridLength(0, GridUnitType.Pixel); GridLength lenAuto = GridLength.Auto; return ((value is bool && (bool)value) ? lenAuto : lenZero); } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } }
<Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition Width="{Binding ElementName=CheckBox1, Path=IsChecked, Converter={StaticResource BooleanToGridLengthConverter}}" /> </Grid.ColumnDefinitions> </Grid>
Example: DoubleToTimeSpanConverter
class DoubleToTimeSpanConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { double hours = (double)value; TimeSpan span = TimeSpan.FromHours(hours); return span; } public object ConvertBack(object value, Type targetType, object parameter, string language) { TimeSpan span = (TimeSpan)value; double hours = span.TotalHours; return hours; } }
Example: NumberToBooleanConverter
class NumberToBooleanConverter : IValueConverter { // Returns True is the provided number is greater than 0. // The value parameter may be double, float, int, or decimal. public object Convert(object value, Type targetType, object parameter, string language) { if (value == null) return false; string str = value.ToString(); double n; if (!(Double.TryParse(str, out n))) return false; return (n > 0.000001); } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } }