<Window
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" >
<Window.Resources>
<WpfApplication1:DoubleToString x:Key="doubleToString" />
<ObjectDataProvider x:Key="convertDistance"
ObjectType="{x:Type WpfApplication1:DistanceConverter }"
MethodName="Convert" >
<ObjectDataProvider.MethodParameters>
<system:Double>0</system:Double>
<WpfApplication1:DistanceType>Miles</WpfApplication1:DistanceType>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<StackPanel>
<TextBlock Text="Enter a distance to convert:"/>
<TextBox Text ="{Binding Source={StaticResource convertDistance},
Path=MethodParameters[0],BindsDirectlyToSource=true,UpdateSourceTrigger=PropertyChanged,
Converter={StaticResource doubleToString}}"/>
<ComboBox Width="80" HorizontalAlignment="Left"
SelectedValue="{Binding Source={StaticResource convertDistance},Path=MethodParameters[1],
BindsDirectlyToSource=true}" >
<WpfApplication1:DistanceType>Miles</WpfApplication1:DistanceType>
<WpfApplication1:DistanceType>Kilometres</WpfApplication1:DistanceType>
</ComboBox>
<TextBlock Text="Result:"/>
<TextBlock Text="{Binding Source={StaticResource convertDistance}}"/>
</StackPanel>
</Window>
//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");
}
}
}