User Tools

Site Tools


technical_notes:public:20131007-wpf-create-usercontrol

Parent

WPF - Create a user control with binding

We will have to use 2 concepts to do this :

  • Dependency property
  • DataContext inheritance
What are the difference between custom control and user control in WPF ?
  • Custom controls are rather special, with the logic being de-coupled from the XAML in order to support templating.
  • User controls are simpler

The difficulty is to expose binding through user control by exposing property.

Reference user control in window

Add the namespace

<Window x:Class="DatePickerCustom.Views.MainWindowView"
        ...
        xmlns:controls="clr-namespace:DatePickerCustom.Controls">
        <Grid>
           <controls:CustomDatePicker />
        </Grid>
</Window>

How to create a bindable property ?

You have to declare a dependency property in file CustomDatePicker.xaml.cs as below :

public String Text
{
    get { return (String)GetValue(TextProperty); }
    set { SetValue(TextProperty, value); }
}
 
public static readonly DependencyProperty TextProperty =
    DependencyProperty.Register("Text", typeof(string),
      typeof(CustomDatePicker), new PropertyMetadata(""));

Why I have to change the Datacontext of Usercontrol ?

@TODO explain through a schema

How to change the Datacontext of Usercontrol ?

Resources

technical_notes/public/20131007-wpf-create-usercontrol.txt · Last modified: 2013/10/08 14:19 by Fabien Arcellier