VS: the basic steps and code implementation of the WPF custom control, vswpf
1. Basic Steps for custom controls:
(In this example, the project name is W; the name of the added custom control is)
1. In the project name in the Solution Explorer window, right-click "add" (Ctrl + Shift +)
2. The following window is displayed. In this window, select "custom control (WPF)", modify the class "name", and click "add"
3. The CustomControl4.cs file and Generic in the Themes folder are generated in this project. xaml file (if it already exists, it will not be regenerated. It will only generate the appropriate XAML tag in the file ),
4. The CustomControl4.cs file and Generic. the xaml file is associated. In the CustomControl4 class of the CustomControl4.cs file (this class can inherit from any parent class and inherit the attributes of its parent class), set the attributes and implement the logic in Generic. design the Style and Template of the control in the xaml File
5. When using this control, you must import the Generic. xaml file in APP. xaml.
6. You can use this control in this project.
Ii. Basic Implementation of custom attributes:
1. In this example, the mcontrol4 class's parent class is changed to the Button class, And the DirectionBackgroundL and DirectionBackgroundR attributes are added, which are used to control the Generic. fill attributes of two Rectangle in ControlTemplate of style in xaml
① Register this property (taking DirectionBackgroundL as an example ):
PublicstaticreadonlyDependencyPropertyDirectionBackgroundLProperty =DependencyProperty.Register("DirectionBackgroundL",Typeof(Brush),Typeof(CustomControl4),NewPropertyMetadata((Brush)M_fwkElement.TryFindResource("@ Blue")));
This function
The first parameter is the name of the registered dependency attribute.
The second is the type of the registered Dependency Property.
The third is the type of the owner of the Dependency Property.
The fourth is the metadata of the dependency property, that is, the default data.
② Declare this attribute in the class and implement its get, set:
Public Brush DirectionBackgroundL
{
Get {return (Brush) GetValue (DirectionBackgroundLProperty );}
Set {SetValue (DirectionBackgroundLProperty, value );}
}
① ② Writing is in no particular order
2. In the Generic. xaml file, when you add a custom control, the system automatically adds a Style template for the newly added control.
You can continue to customize the controls you want based on the template.
The red box in the figure shows the property to be bound. This control can be used when the property is bound.
This article focuses on basic knowledge. If you have any shortcomings, please kindly advise. Thank you!