C# multiple custom controls types recognizing
My question is based on an example from WPF, but, I think, it's more about C# in general.
Suppose I have a WPF app where I use several types of Custom Controls, let it be CustControl1
, CustControl2
, CustControl3
. The page can dynamically load the XAML with controls of either of the types.
List<CustControl1> MyCustControls = this.Descendents().OfType<CustControl1>().ToList();
foreach (CustControl1 cntr in MyCustControls)
{
...
In the above code the CustControl1
type is explicitly defined, and if other types of Custom Controls are loaded on the page (of CustControl2
or CustControl3
type), the code will not recognize it.
My level of C# knowledge is insufficient to find out how to sol开发者_Python百科ve such a problem of multiple type recognizing. Or is it possible in C# at all?
If I understand your question correctly, this is a basic OOP concept.
You would pass in all of your controls as their parent class (UserControl, or even Control), or an interface they all implement (IControl for example)
then, if the method you are trying to call exists in the parent, you can just call it:
List<UserControl> MyCustControls = this.Descendents().OfType<UserControl>().ToList();
foreach (UserControl cntr in MyCustControls)
{
cntr.SomeShareMethod()
or, if you need to call it explicitly on concrete implementation, you can do this:
List<Control> MyCustControls = this.Descendents().OfType<Control>().ToList();
foreach (Control cntr in MyCustControls)
{
if (cntr is CustControl1)
((CustControl1)cntr).SomeSpecificMethod()
you can do
var controls = this.Descendents().OfType<CustControl1>().Cast<Control>()
.Union(this.Descendents().OfType<CustControl2>().Cast<Control>())
.Union(this.Descendents().OfType<CustControl3>().Cast<Control>())
.ToList();
精彩评论