WPF custom Controls (iv) custom controls

Source: Internet
Author: User

In real-world work, the controls provided by WPF do not fully meet the different design requirements. At this point, we need to design our own custom controls.

Here LZ summarizes some of their own ideas, features are as follows:

    • Coupling
    • Uitemplate
    • Behaviour
    • Function Package

For example, in the project we often use the mixer volume bar, write a custom control to simulate the mixer volume bar.

Custom control singnallight, enabling functionality

    • Receives a value from the outer range 0~100
    • Real-time display of received values
    • Value range 0~50 Display green, 50~85 display yellow, 85~100 red, no value display Brown
    • You can drag the control on the parent control

 Public classSingnallight:contentcontrol { Public intValuea {Get{return(int) GetValue (Valueaproperty); }            Set{SetValue (valueaproperty, value);} }             Publicsingnallight () { This. AllowDrop =true; }        Staticsingnallight () {Defaultstylekeyproperty.overridemetadata (typeof(Singnallight),NewFrameworkpropertymetadata (typeof(Singnallight))); }    }

Valuea is an attribute that accepts an external value

2. Replication Control Uitemplate

 1 <style targettype= "{x:type control:singnallight}" > 2 <setter property= "RenderTransform" > 3 <Setter.Value> 4 <translatetransform x= "{Binding path=x,relativesource={relativesource ances Tortype={x:type Control:singnallight}}} "5 y=" {Binding path=y,relativesource={relative         Source Ancestortype={x:type Control:singnallight}}} "/> 6 </Setter.Value> 7 </Setter> 8                     <setter property= "Template" > 9 <setter.value>10 <controltemplate>11 <controltemplate.resources>12 <control:singnallightstatusconverter x: key= "Colorconverter" ></control:singnallightstatusconverter>13 <control:singnallightval Ueconverter x:key= "Valueconverter" ></control:singnallightvalueconverter>14 </ControlTempla Te.      Resources>15               <stackpanel>16 <textblock text= "{Binding Path=valuea,relativesource={relat Ivesource Ancestortype={x:type Control:singnallight}}} "></textblock>17 <textblock Text                             = "></textblock>18" <border x:name= "BD1" 20 height= "{Binding path=lightheight,relativesource={relativesource ancestortype={x:type control:singnall Ight}}} "snapstodevicepixels=" True "borderbrush=" Black "Border                                                       thickness= "1" background= "Transparent" >23 <rectangle fill= "{Binding path=valuea,24 Relativesource={relativesource Ancestortype={x:type Control:singnallight}                             },25 Converter={staticresource Resourcekey=colorconverter}} "26           Verticalalignment= "Bottom" >27 <rectangle.height>28                                         <multibinding converter= "{StaticResource resourcekey=valueconverter}" >29 <binding path= "Valuea" relativesource= "{RelativeSource Ancestortype={x:type Control:singnallight}}" >&l                                      t;/binding>30 <binding path= "Height" elementname= "BD1" ></binding>31                             </multibinding>32 </rectangle.height>33 </rectangle>34 </border>35 <text Block text= "0" ></textblock>36 </stackpanel>37 </controltemplate>3 8 </setter.value>39 </setter>40 </Style>

3. Accept value judgment, Singnallight implements UI rendering bindings by implementing IValueConverter and override Arrange & Measure Methods

 1 public class Singnallightstatusconverter:ivalueconverter {2 public object Convert (object value, Type tar GetType, object parameter, System.Globalization.CultureInfo culture) {3 SolidColorBrush result = Brushes.tran Sparent; 4 if (value. GetType () = = typeof (int)) {5 var color = System.Convert.ToInt32 (value); 6 if (Color < result = Brushes.green; 7 Else if (Color < >= && color) result = Brushes.yellow; 8 Else if (color <= && color >=) result = brushes.red;  9 Else result = brushes.gray;10}11 return result;12}13             Object Convertback (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {15 throw new NotImplementedException ();}17}18 public class Singnallightvalueconverter:imultival       Ueconverter {20  public Object Convert (object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) {21 Double result = 0;22 if (values[0]. GetType () = = typeof (int) && values[1].             GetType () = = typeof (double)) {result = (double) values[1]/+ System.Convert.ToDouble (Values[0]); 24 }25 return result;26}27 object[] Convertback (object value, type[] Targe          Ttypes, object parameter, System.Globalization.CultureInfo culture) {throw new NotImplementedException (); 30 }31}
1         protected override size measureoverride (size constraint) {2             if (ActualHeight > 0) lightheight = ActualHeight *. 7;3             return base. MeasureOverride (constraint); 4         }5 6         protected override size Arrangeoverride (size arrangebounds) {7             return Base. Arrangeoverride (arrangebounds); 8         }


4. The control supports drag-and-drop, overwrite the Mousedown,mousemove,mouseup method. The benefit of this writing is that if you implement drag in the event of a parent control, the logic can be confusing if the parent control has more than one object.

1         protected override void OnMouseMove (MouseEventArgs e) {2             base. OnMouseMove (e); 3             if (E.leftbutton = = mousebuttonstate.pressed) {4                 _currentpoint = E.getposition (this); 5                 X + = _ Currentpoint.x-_startpoint.x; 6                 Y + = _currentpoint.y-_startpoint.y; 7             } 8         } 9         protected override void OnMouseDown (mousebuttonevent Args e) {one             base. OnMouseDown (e);             _startpoint = E.getposition (this);             CaptureMouse ();         }15         protected override void OnMouseUp (MouseButtonEventArgs e) {             base. OnMouseUp (e);             Releasemousecapture ();         

Custom Control Series Blog Links:

WPF Custom Control (i) Control classification
WPF Custom Control (ii) control classification
WPF custom Controls (iii) control classification
WPF custom Controls (iv) control classification
WPF custom Controls (v) Control classification

WPF Custom Control (iv) custom control

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.