Re: property exists (OnPaint followup)

Fabian Schmied <[email protected]>
Newsgroups gmane.comp.windows.devel.dotnet.winforms
Message-ID <[email protected]>
> As a follow on to my painting question, I need to obtain the 'BackColor'
> of the hosting 'canvas' control.  For the VS controls, this is simple
> since there is a BackColor property.  For other controls that changed
> the name of the 'BackColor' property or that have the BackColor property
> another level deep in their object model, it isn't quite as simple.
>
> For example, the infragistics control I want to use as the canvas
> exposes the BackColor property inside an 'Appearance' property.
>
> So for the System.Windows.Forms.Panel object, I get the BackColor from
>
> Color myColor = _canvas.BackColor;
>
> For the Infragistics.WinGroupBox object, I get the BackColor from...
>
> Color myColor = _canvas.Appearance.BackColor;
>
> If the 'Appearance' property exists for the object assigned to _canvas,
> then I will use it.  So what I am asking is, how do I check to see if
> the object '_canvas' has a property called 'Appearance'?

You'll notice when the C# compiler gives an error.

In a programming language like C#, if you have a canvas variable of
type "Control", you can only invoke methods directly supported by the
Control class.

I.e.:
Control _canvas = ...;
Color myColor1 = _canvas.BackColor; // compiles
Color myColor2 = _canvas.Appearance.BackColor; // gives a compilation error

In order to access the Appearance property, the "_canvas" variable
must be of a type which supports that property. In C#, you need to
cast the object to such a type. If you are not sure the cast will
succeed, you can use the "is" or "as" operators to test it:

Control _canvas = ...;
...
Color myColor;
// test whether _canvas implements the InfragisticsControl type
InfragisticsControl _infragisticsControl = _canvas as InfragisticsControl;
if (_infragisticsControl != null)
{
  // yes, so use Appearance
  myColor = _infragisticsControl.Appearance.BackColor;
}
else
{
  // no, use Color
  myColor = _canvas.BackColor;
}

(Note that I don't know Infragistics' controls, so the solution I'm
proposing might not work exactly that way.)

Regards,
Fabian
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.