1. Create WPF User control library. It will create such class
partial class MySuperTextBox : UserControl
2. Create DependencyProperty via propdp
public int MyProperty
{
get { return (int)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(int), typeof(ownerclass), new UIPropertyMetadata(0));
3. No you can change the dp to the type you need
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MySuperTextBox), new FrameworkPropertyMetadata("red", new PropertyChangedCallback(qwe)));
4. The difference between UIPropertyMetadata to FrameworkPropertyMetadata is that UIPropertyMetadata does only initialize the dp , FrameworkPropertyMetadata can also fire events.
5. new FrameworkPropertyMetadata("red", new PropertyChangedCallback(qwe)));
qwe is a function with this signature (need to do that manually).
private static void qwe(DependencyObject obj,DependencyPropertyChangedEventArgs args)
{
MySuperTextBox mstb = obj as MySuperTextBox;
mstb.txt.Text = args.NewValue.ToString();
}
6. That closed the User Control.
7. If you want to use this control in a WPF application.
8. Create WPF application
9. You can see the user control in the toolbox
10. Drag it to your XAML
11. This will
a. Add reference
b. Add xmlns : xmlns:my="clr-namespace:MyControl;assembly=MyControl">
c. Add the control to the XAML <my:MySuperTextBox Name="mySuperTextBox2" />
d. You can bind the dp in the user control to other data (textBox1 is a TextBox Control):
<my:MySuperTextBox Name="mySuperTextBox1" Text="{Binding ElementName=textBox1, Path=Text}" />
12. That’s it.