WPF UserControl with generic code-behind

Viewed 15084

I have this code behind:

CustomUserControl.xaml.cs

namespace MyProject
{
    public partial class CustomUserControl<T> : UserControl
    {
        ...
    }
}

and this xaml:

CustomUserControl.xaml

<UserControl x:Class="MyProject.CustomUserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Grid>

</Grid>

It doesn't work since the x:Class="MyProject.CustomUserControl" doesn't match the code-behind's generic class definition. Is there some way to make this work?

4 Answers

I ended up with an extra helper class, this is not a UserControl. It does the job well for a simple custom UserControl that needs a Generic Type.

So the UserControl, for instance UCMoveObject, has an InitFunction that returns to me the Helper instance:

// In the UCMoveObjects UserControl Class.
public UCMoveObjectsHelper<T> InitUCMoveObject<T>(List<T> argAllList, List<T> argSelectedList)
{
     return new UCMoveObjectsHelper<T>(this, argAllList, argSelectedList);
}

Then in the helper class I place all the code for making the user control work.

public class UCMoveObjectsHelper<T>
{

public UCMoveObjectsHelper(UCMoveObjects argUserControl, List<T> argAllList, List<T> argSelected)
{
   _ucMoveObjects = argUserControl;

   // Example reaching the usercontrol
   _ucMoveObjects.listBox.SelectionChanged += LbAll_SelectionChanged;

   // Do whatever I want with T
}

public List<T> ReturnSelected()
{
     // Code that return a List<T>;
}

}

In the MainWindow.xaml i place a usercontrol in the window. Then in code I do the following:

  _ucMovingObjectsHelper = ucMovingObjects.InitUCMoveObject<TblUsers>(tempListAll, tempListSelected);

And later in my code I can call:

var tempSelectedList = _ucMovingObjectsHelper.ReturnSelected();
Related