Monday, January 14, 2013

WebSDK: Supporting User Applied WebStyles

One area of creating custom controls that developers often forget is dealing with user applied WebStyles. If your control will allow user defined styles, it is important that you add the correct attributes to your controls (if not, see the SDK docs for instructions on how to hide the Style property in your control).

User defined WebStyles are sent to the browser as class styles, so to initially render the correct style, you would add an attribute to your control's HTML tag:

dim tag as string
tag = "<div id=""" + self.controlid + """"

if not self.style.IsDefaultStyle then
  tag = tag + " class=""" + self.style.name + """"
end if

tag = tag + "></div>"

return tag

When a control has the default style, there is a method on the WebStyle class named IsDefaultStyle which will return true. In that case, you don't need to apply the style because it should match the style that was passed into SetupCSS.

In addition, users expect to have the ability to change styles at runtime. To support runtime changes, you should implement the FrameworkPropertyChanged event and check the style name like this:

Select Case Name
Case "Style"
  Dim st as WebStyle = WebStyle(value)
  If right(st.name,8) <> "_default" then
    ExecuteJavascript("RS.addClass('" + me.controlid + "','" + st.name + "');")
  End If
End Select

Lastly, if you want to support the case where a user removes a style at runtime (sets it to nil), you'll need to keep track of the last class name that was applied to your control. Add a property to your control:

Private Property mLastStyle as String = ""

Then add some code to the SetupHTML event:


dim tag as string
tag = "<div id=""" + self.ControlID + """"

if not self.style.IsDefaultStyle then

  tag = tag + " class=""" + self.style.name + """"
  mLastStyle = self.style.name
end if


tag = tag + "></div>"
  
return tag

and some code to the FrameworkPropertyChanged event:

Select Case Name
Case "Style"
  Dim st as WebStyle = WebStyle(value)
  If not self.style.IsDefaultStyle then
    ExecuteJavascript("RS.addClass('" + _
      me.controlid + "','" + st.name + "');")
    mLastStyle = st.name
  Else
    If mLastStyle<>nil then
      ExecuteJavascript("RS.removeClass('" + _
        me.controlid + "','" + mLastStyle + "');")
    End If
  End If
End Select

Now your control should work with user defined styles!

No comments: