public
class
WeightConverter
:
IMultiValueConverter
{
public
object
Convert(
object
[] values,
Type
targetType,
object
parameter,
CultureInfo
culture)
{
if
(
null
== values || 2 != values.Length )
{
return
""
;
}
string
unit =
""
;
string
temp = values[0].ToString();
if
(
String
.IsNullOrEmpty(temp))
{
return
""
;
}
if
(0 <= temp.IndexOf(
"lb"
))
{
unit =
"lb"
;
}
else
if
(0 <= temp.IndexOf(
"kg"
))
{
unit =
"kg"
;
}
else
{
return
""
;
}
string
number =
""
;
number = temp.Substring(0, temp.IndexOf(unit));
//KG
if
((
bool
)values[1])
{
measurementUnit =
"kg"
;
}
else
//LB
{
measurementUnit =
"lb"
;
}
return
ConvertToTargetValue(number, unit, measurementUnit);
}
private
string
measurementUnit =
""
;
public
object
[] ConvertBack(
object
value,
Type
[] targetTypes,
object
parameter,
CultureInfo
culture)
{
string
temp = value.ToString();
if
(
String
.IsNullOrEmpty(temp))
{
return
new
object
[]{
DependencyProperty
.UnsetValue,
DependencyProperty
.UnsetValue};
}
if
(
String
.IsNullOrEmpty(measurementUnit))
{
measurementUnit = (
PAFEContainee
.MainDataContext
as
MainViewModel
).PRCfgVM.IsDefaultKilogram ?
"kg"
:
"lb"
;
}
object
[] list =
new
object
[2];
list[0] = value.ToString() + measurementUnit;
list[1] = measurementUnit.Equals(
"kg"
) ?
"true"
:
"false"
;
return
list;
}
private
string
ConvertToTargetValue(
string
before,
string
beforeUnit,
string
afterUnit)
{
string
result =
""
;
if
(beforeUnit.Equals(afterUnit))
{
return
before;
}
switch
(afterUnit)
{
case
"lb"
:
result = ConvertKgToPound(before).ToString();
break
;
case
"kg"
:
result = ConvertPoundToKg(before).ToString();
break
;
default
:
break
;
}
return
result;
}
private
double
ConvertPoundToKg(
string
pound)
{
double
kg = 0.4536 *
double
.Parse(pound);
return
kg;
}
private
double
ConvertKgToPound(
string
kg)
{
double
pound = 2.20 *
double
.Parse(kg);
return
pound;
}
}
///////ValidationRule
public
override
ValidationResult
DoValidate
(
object
value
,
CultureInfo
cultureInfo
)
{
try
{
//string field = value.ToString().Trim();
string
field
= (
value
as
object
[])[0].
ToString
();
string
pattern
=
@"^([1-9]|[1-9][0-9]|[1-5][0-9][0-9]|600)((kg)|(lb))$"
;
Regex
reg
=
new
Regex
(
pattern
,
RegexOptions
.
IgnoreCase
);
if
(
field
.
Length
<= 0 ||
false
==
reg
.
IsMatch
(
field
))
{
return
new
ValidationResult
(
false
,
"Please input a number, for example '60'"
);
}
else
{
return
ValidationResult
.
ValidResult
;
}
}
catch
{
return
new
ValidationResult
(
false
,
"Patient weight convert failed."
);
}
}