How to override SharePoint styles for custom web parts?
Here is a web part that allows user to provide a CSS file for overriding the stylesused in the web part.
For simplicity, I selected the style, ms-menutoolbar which can be seen on the toolbar of viewlsts.aspx page (on other pages as well). The web part has a table with two rows – one of them is applied with ms-menutoolbar and another is applied with ms-menutoolbar and custom style class, overridden-menutoolbar (we will see how this can be used to override the styles). A web part property, CustomCssUrl is provided to select custom CSS file. If user wants to override the default style, he can specify the custom CSS file location or leave blank to use the default style.
Highlighted code below method makes the trick.
writer.Write(“<td class=’ms-menutoolbar overridden-menutoolbar‘>”);
The definition for overridden-menutoolbar class is present in the CSS file:
.overridden-menutoolbar
{
BACKGROUND-IMAGE: url(/_layouts/images/menubuttonhover.gif);
}
This overrides only BACKGROUND-IMAGE style and other styles specified in ms-menutoolbar will remain
unaltered. If web part cannot find overridden-menutoolbar then, ms-menutoolbar will be applied without any change.
Below is the web part and its source code.
CSS File:
.overridden-menutoolbar
{
BACKGROUND-IMAGE: url(/_layouts/images/menubuttonhover.gif);
}
Web Part:
public class OverrideStyle : System.Web.UI.WebControls.WebParts.WebPart
{
private string _customCssUrl;
private CssLink _customCss;
[WebBrowsable(true)]
[Bindable(true)]
[FriendlyName(“Custom CSS Url”)]
[Category(“Style”)]
[Personalizable(PersonalizationScope.Shared)]
public string CustomCssUrl
{
get{ return _customCssUrl; }
set{ _customCssUrl = value; }
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
if (_customCss != null)
{
_customCss.RenderControl(writer);
}
writer.Write(“<table width=’100%’>”);
writer.Write( “<tr>”);
writer.Write( “<td class=’ms-menutoolbar’>”);
writer.Write( “Original Style”);
writer.Write( “</td>”);
writer.Write( “</tr>”);
writer.Write( “<tr>”);
writer.Write( “<td height=’15px’>”);
writer.Write( “</td>”);
writer.Write( “</tr>”);
writer.Write( “<tr>”);
writer.Write( “<td class=’ms-menutoolbar overridden-menutoolbar’>”);
writer.Write( “Overridden Style”);
writer.Write( “</td>”);
writer.Write( “</tr>”);
writer.Write(“</table>”);
}
protected override void OnPreRender(EventArgs e)
{
if (!string.IsNullOrEmpty(_customCssUrl))
{
_customCss = new CssLink();
_customCss.ID = “customCss”;
_customCss.DefaultUrl = _customCssUrl;
this.Controls.Add(_customCss);
}
}
}
-
Archives
- March 2010 (2)
- February 2010 (1)
- May 2009 (1)
-
Categories
-
RSS
Entries RSS
Comments RSS