Friday, February 12, 2010

 

Overloading Properties

I've been writing a custom control that takes a Fraction in the XAML supplied as a Point, (X,Y). I don't want it to freak when the Y isn't supplied, since, in my case this just means Y is equal to 1.
I came across this thread while trying to make this control more user friendly.
http://bytes.com/topic/c-sharp/answers/258911-overloading-properties

The last option of making the Property of type Object is what did the trick for me. Below is how I overloaded my property to accept both double and Point.

private Point ratioToFirst;
public Object RatioToFirst
{
get { return this.ratioToFirst; }
set
{
if (value is Point)
this.ratioToFirst = (Point)value;
else if (value is double || value is int)
this.ratioToFirst = new Point((double)value, 1);
else //values from XAML will usually be taken in as strings
{
string input = value.ToString();
try
{
if (input.Contains(",") || input.Contains("/") || input.Contains(":")) value = ConvertToPoint(input);
else value = Convert.ToDouble(value);
if (value is Point && this.ratioToFirst != (Point)value)//check if the value changed
this.ratioToFirst = (Point)value;
else if (value is double)
this.ratioToFirst = new Point((double)value, 1);
}
catch //unsupported or malformed string
{
this.ratioToFirst = new Point(-1, 1);
}
}
}
}
private Point ConvertToPoint(string input)
{
char delimiter = ','; //find what is used to delimit the two numbers of the Point
if (input.Contains("/")) delimiter = '/';
else if (input.Contains(":")) delimiter = ':';

string x = input.Split(delimiter)[0],
y = input.Split(delimiter)[1];
return new Point(Convert.ToDouble(x), Convert.ToDouble(y));
}

This property can be utilized with the following XAML




Labels: , , ,


Comments: Post a Comment

Subscribe to Post Comments [Atom]





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]