x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:WpfApplication1="clr-namespace:WpfApplication1"
Title="WPF" Width="240" Height="150" >
ObjectType="{x:Type WpfApplication1:DistanceConverter }"
MethodName="Convert" >
0
Miles
Path=MethodParameters[0],BindsDirectlyToSource=true,UpdateSourceTrigger=PropertyChanged,
Converter={StaticResource doubleToString}}"/>
SelectedValue="{Binding Source={StaticResource convertDistance},Path=MethodParameters[1],
BindsDirectlyToSource=true}" >
Miles
Kilometres
//File:Window.xaml.cs
using System;
using System.Windows.Data;
namespace WpfApplication1
{
public class DoubleToString : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,System.Globalization.CultureInfo culture)
{
if(value != null)
{
return value.ToString();
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter,System.Globalization.CultureInfo culture)
{
string strValue = value as string;
if(strValue != null)
{
double result;
bool converted = Double.TryParse(strValue, out result);
if(converted)
{
return result;
}
}
return null;
}
}
public enum DistanceType
{
Miles,
Kilometres
}
public class DistanceConverter
{
public string Convert(double amount, DistanceType distancetype)
{
if(distancetype == DistanceType.Miles)
return (amount * 1.6).ToString("0.##") + " km";
if(distancetype == DistanceType.Kilometres)
return (amount * 0.6).ToString("0.##") + " m";
throw new ArgumentOutOfRangeException("distanceType");
}
}
}