Monday, September 3, 2012

WPF custom control and adding DependencyProperty to custom control

To create custom control in WPF, choose WPF Custom Control Library project in VS2010. Then rename the default added class to your choice. I am trying to create a custom list box with few user added properties in it. Then add a WPF project which will use this custom list box in it. So my solution structure is as follows –

Now I am going to add dependency properties in the class file. These properties will be then available in Properties window once you use the control in any WPF application.

Following are the  properties I added –
public class AmsCheckBoxList : ListBox
        static AmsCheckBoxList()
            DefaultStyleKeyProperty.OverrideMetadata(typeof(AmsCheckBoxList), new FrameworkPropertyMetadata(typeof(AmsCheckBoxList)));           

       public string MutuallyExclusiveIndexes
            get { return (string)GetValue(MutuallyExclusiveIndexesProperty); }
            set { SetValue(MutuallyExclusiveIndexesProperty, value); }

        // Using a DependencyProperty as the backing store for MutuallyExclusiveIndexes.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MutuallyExclusiveIndexesProperty =
            DependencyProperty.Register("MutuallyExclusiveIndexes", typeof(string), typeof(AmsCheckBoxList), new UIPropertyMetadata(null));     


In Visual Studio 2010, type "propdp" (without the double quotes) and press the Tab key, the Dependency Property snippet will be generated, then just fill in the missing bits.
Now build the application, add reference of WPF Custom Control Library to the WPF application. The control will be automatically get available in the Toolbox as shown –


Add the control in WPF MainWindows.xaml file and open properties window for custom control. Here you can view the user defined custom dependency property listed in Properties window.


Hope this helps.

Happy Controlling!!!

No comments:

Post a Comment