WPF Custom Control tutorial

Creating a custom control may be necessary in some circumstances where you want to persist a design pattern such as MVVM. In this scenario you will try to bind your data to your control and build it that way. In order to do this it is best to first create a class or WPF Custom Control. Like so:

Public Class CustomGrid:Grid{}

The next step is to work with a "DependencyProperty". I'm not going to go in to detail about this property but if you do some research you'll find that it delivers quite a bit of flexibility and will eventually allow us to bind data in design time.

publicreadonlystaticDependencyProperty MyPropertyValue = DependencyProperty.Register("MyWrapperProperty", typeof(TheTypeofContainer), typeof(CustomGrid), newFrameworkPropertyMetadata(new TheTypeofContainer(), OnCurrentPropertyChanged));

After this make sure you have an OnCurrentPropertyChanged Event handler in order to Build your control in runtime.

privatestaticvoid OnCurrentPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e){ //Build your stuff here}

And last but not least, you will need a wrapper to allow design time binding towards the "DependencyProperty".

//Wrapper for DependencyProperty

publicWerkplanningCollection ItemsSource{

get{return (TheTypeOfContainer)GetValue(TheTypeOfContainer);}
set{         SetValue(TheTypeOfContainerValue, value);   }

}

Once all this is finished you can just use a regular "Binding Path" in your Xaml file. Offcourse you will still need a resource that delivers the object to Xaml. (A ViewModel and a reference to this resource from your xaml file)

PS. "TheTypeOfContainer" is here the type or class that you will use as your datasource.

 

 

Leave a Reply