c# - Creating a custom UI element in WPF -
i have several textboxes
labels
in code implemented following xaml:
<dockpanel horizontalalignment="right"> <textblock foreground="black" padding="0,0,10,0">serial number:</textblock> <textbox width="150" isreadonly="true" borderbrush="gainsboro" height="20"></textbox> </dockpanel>
i can reduce of copied code doing like:
<dockpanel horizontalalignment="right"> <textblock style="{staticresource cstmtextboxlbl}">serial number:</textblock> <textbox style="{staticresource cstmtextbox}"></textbox> </dockpanel>
but still lengthy. possible like:
<controls:cstmtextbox style="{staticresource cstmtextbox}" labeltext="serial number:" text=""/>
where cstmtextbox
implement whatever xaml needed same visual effect once, , access both textblock
text , textbox
text in code. such as
cstmtextbox textbox; textbox.labeltext = "serial number:"; string some_text = textbox.text; textbox.text = "....";
a usercontrol or customcontrol serves needs. code customcontrol.
c#:
public class cstmtextbox : control { public string labeltext { { return (string)getvalue (labeltextproperty); } set { setvalue (labeltextproperty, value); } } public static readonly dependencyproperty labeltextproperty = dependencyproperty.register ("labeltext", typeof (string), typeof (cstmtextbox), new propertymetadata (string.empty)); public string text { { return (string)getvalue (textproperty); } set { setvalue (textproperty, value); } } public static readonly dependencyproperty textproperty = dependencyproperty.register ("text", typeof (string), typeof (cstmtextbox), new propertymetadata (string.empty)); }
xaml:
<style targettype="{x:type controls:cstmtextbox}"> <setter property="template"> <setter.value> <controltemplate targettype="{x:type controls:cstmtextbox}"> <dockpanel horizontalalignment="right"> <textblock foreground="black" padding="0,0,10,0" text="{templatebinding labeltext}"/> <textbox width="150" isreadonly="true" borderbrush="gainsboro" height="20" text="{templatebinding text}"/> </dockpanel> </controltemplate> </setter.value> </setter> </style>
add style resources , use new control:
<controls:cstmtextbox labeltext="abcde" text="1234"/>
Comments
Post a Comment