Tech blog

Solving problems

About
Contact

Silverlight: inherit a generic class from UserControl

leave a comment

Note! This blog post is just an idea than well tested solution, more a review that detailed description.
In Silverlight UserControl and Page classes are usually used with xaml. Root tags in xaml define the type, like so:

xaml
<UserControl x:Class="MyView">
...
</UserControl>

code-behind
namespace MyNamespace
{
  class MyView : UserControl
}

Sometimes, developers want to extend UserControl, i.e. as View by MVVM pattern.

xaml
<v:ViewBase x:Class="MyNamespace.MyView" xmlns:v="clr-namespace:MyNamespace">
...
</v:ViewBase>

code-behind
namespace MyNamespace
{
  class MyView : ViewBase /* ViewBase is a custom class */
}

Step further, every View should have it’s specialized model (ViewModel), thus base class could integrate a Model property. To avoid casting one should use generics, like ViewBase<MyViewModel>.

xaml
<!-- There's a problem, generics cannot be written in xaml. -->

code-behind
namespace MyNamespace
{
  class MyView : ViewBase<MyViewModel> /* ViewBase is a custom class */
}

Generics cannot be written directly in xaml? There is a workaround:
1. Use a wrapper, described here
2. Create a new non-generic class, like in this sample:

xaml
<v:MyViewBase x:Class="MyNamespace.MyView" xmlns:v="clr-namespace:MyNamespace">
...
</v:MyViewBase>

code-behind
namespace MyNamespace
{
  class MyView : MyViewBase
}

public abstract class MyViewBase : ViewBase<MyViewModel>
{
  /* non-generic class */
}

Appendix: ViewBase<TViewModel> class

public abstract class ViewBase<TViewModel> : UserControl, INotifyPropertyChanged where TViewModel : ViewModelBase, new()
{
	private TViewModel model;
	public TViewModel Model
	{
		get
		{
			if (this.model == null)
			{
				this.model = new TViewModel();
				base.DataContext = this.model;
			}
			return this.model;
		}
		set
		{
			if (this.model != value)
			{
				this.model = value;
				base.DataContext = this.model;
				OnPropertyChanged("Model");
			}
		}
	}
}

References:

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)
Share and Enjoy:
  • Twitter
  • Facebook
  • Digg
  • Technorati
  • LinkedIn
  • del.icio.us
  • Print

Leave a Reply