I am writing a custom ToolStripProfessionalRenderer
Take for example, the following override:
protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
{
if(e.ToolStrip is MenuStrip)
{
// It never is. It's always ToolStripDropDownMenu
}
}
I guess that OnRenderImageMargin is called by the drop down menu since this is what will be rendered, however I want to get the parent ToolStrip/MenuStrip/StatusStrip that caused the OnRenderImageMargin call.
Is this possible?
I thought the e.ToolStrip.Parent property would be the key, but it's always null.
One option is to create a constructor in your ToolStripProfessionalRenderer, and pass in a reference to the control.
class CustomRenderer : ToolStripProfessionalRenderer
{
// All those controls derive from ToolStrip so we can use the base class here
private ToolStrip ts;
public CustomRenderer(ToolStrip ts)
{
this.ts = ts;
}
protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
{
if (ts is MenuStrip)
{
}
else if (ts is StatusStrip)
{
}
else // ts is ToolStrip
{
}
}
Then pass a reference in when you instantiate it:
toolStrip1.Renderer = new CustomRenderer(toolStrip1);
statusStrip1.Renderer = new CustomRenderer(statusStrip1);
An alternative option, modified from this answer.
Forget the ctor and test the Owner repeatedly until you get the correct parent control:
protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
{
ToolStrip owner = e.ToolStrip;
while (owner is ToolStripDropDownMenu)
owner = (owner as ToolStripDropDownMenu).OwnerItem.Owner;
if (ts is MenuStrip)
{
}
else if (ts is StatusStrip)
{
}
else // ts is ToolStrip
{
}
}
Related
I am creating a custom control in my C# application in order to add a new property (MyProperty below). It is inheriting from Label. One thing I would like it to do, is display at a particular size when I drag it on to my form (200x132). I'd also like it to display no text. However, no matter how I try to do this, it doesn't seem to work. I am able to set BackColor and BorderStyle with no problem, however. I'm fairly new to C#, so maybe I'm missing something obvious.
Here is my code:
using System.Drawing;
using System.Windows.Forms;
namespace MyProgram
{
public enum MyEnum
{
Value1, Value2, Value3
}
public partial class MyControl : Label
{
public MyControl()
{
BackColor = Color.LightCoral;
BorderStyle = BorderStyle.FixedSingle;
AutoSize = false;
Size = new Size(200, 132);
Text = "";
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
private MyEnum myProperty;
public MyEnum MyProperty
{
get { return myProperty; }
set { myPropery = value; }
}
}
}
The answer provided via Dispersia's link has a bug, in my opinion. The text reset should happen once and then whatever a user does after that shouldn't matter. In Dispersia's link you can't actually set the text back to the control name because it will keep blanking it out.
The answer provided by cramopy doesn't technically answer your question, it is a way to do it by using the defaults on a UserControl though. You'll also need to bind the Text property of the UserControl to the label's.
The following should work while inheriting from a Label and will only reset the Text property once.
public partial class MyControl : Label
{
#region fields
private IComponentChangeService _changeService;
private bool canResetText = false;
#endregion
#region properties
protected override Size DefaultSize
{
get { return new Size(200, 132); }
}
[Browsable(false)]
public override bool AutoSize
{
get { return false; }
set { base.AutoSize = false; }
}
public override ISite Site
{
get { return base.Site; }
set
{
base.Site = value;
if (!base.DesignMode)
return;
this._changeService = (IComponentChangeService)base.GetService(typeof(IComponentChangeService));
if (this._changeService != null)
this._changeService.ComponentChanged += new ComponentChangedEventHandler(this.OnComponentChanged);
}
}
#endregion
#region constructors
public MyControl()
{
base.BackColor = Color.LightCoral;
base.BorderStyle = BorderStyle.FixedSingle;
}
#endregion
#region methods
protected override void InitLayout()
{
base.InitLayout();
this.canResetText = true;
}
private void OnComponentChanged(object sender, ComponentChangedEventArgs ce)
{
if (ce.Component != null &&
ce.Component == this &&
ce.Member.Name == "Text" &&
base.DesignMode &&
this.canResetText)
{
((MyControl)ce.Component).Text = string.Empty;
this.canResetText = false;
if (this._changeService != null)
this._changeService.ComponentChanged -= new ComponentChangedEventHandler(this.OnComponentChanged);
}
}
#endregion
}
#Dispersia reply only answers the myControl1 thing. (deleted meanwhile)
Here comes a full guide for solving your problem:
Add a new UserControl named MyLabel
Change the following within Designer Mode:
BorderStyle:= FixedSingle
Size:= 200; 132
Now Drag&Drop a new Label onto the control
Edit those Label values (also within Designer Mode):
AutoSize:= false
BackColor:= LightCoral
Dock:= Fill
Text:= clear/empty this box!! (don't write this inside the box, you really have to clear it!)
TextAlign:= MiddleCenter
Just recompile your project && add a MyLabel control from the Toolbar.
Now it show up as you wanted!!
I have these objects in my project:
SchedulerList
SchedulerListItem
SchedulerListItemDetails
each one is a win forms control, which are used in forms of my application. The SchedulerList holds SchedulerListItems and each item can have SchedulerListItemDetails.
my code goes as follows:
//creating my initial list form
FrmListTesting f = new FrmListTesting();
f.Show();
The form has only one button that has a hard-coded parameter for testing purposes, as well as a SchedulerList control taht will hold the list items.
When the button is clicked the form does the following:
private void button1_Click(object sender, EventArgs e)
{
var control = this.Controls[1] as SchedulerList;
var path = #"D:\Share\Countries.txt";
var sli = new SchedulerListItem(path);
control.AddItem(sli);
}
my SchedulerListItem constuctor goes as follows:
public SchedulerListItem(string path)
{
InitializeComponent();
this.Name = Path.GetFileNameWithoutExtension(path);
this.SourcePath = path;
this.DestinationPath = GetDestinationPath(path);
}
And the AddItem method is defined as:
public void AddItem(SchedulerListItem item)
{
this.flPanel.Controls.Add(item);
}
The add item method works as intended, displays all the data that was required and displays it in the UI. The list item has a button that brings up the details form as such:
//the form constructor
public FrmSchedulerItemDetails(SchedulerListItem item)
{
InitializeComponent();
this.detailsControl = new SchedulerListItemDetails(item, this);
}
//control constructor
public SchedulerListItemDetails(SchedulerListItem item, Form owner)
{
InitializeComponent();
this.SourcePath = item.SourcePath;
this.DestinationPath = item.DestinationPath;
this.OldFormat = item.OldFormat;
this.ExportToExcel = item.ExportToExcel;
this.owner = owner;
this.underlyingItem = item;
}
And now the problem. After the SchedulerListItemDetails constructor is called and the data "gets initialized", when i look at the data inside the object its set to default values. it seams that everything that I set after InitializeComponent(); gets ignored.
things that i have tried:
hard-coding the values to see if primitives get passed correctly
settings breakpoints on every InitializeComponent() method to see the stack trace associated with setting to default values
none of the methods show any results... I know that if i use a form directly instead of using a control within a from i can set the values the way i want to, but I'm very confused as to why this other method with controls doesn't work.
EDIT 1:
the code for SchedulerListItemDetails:
public partial class SchedulerListItemDetails : UserControl
{
public SchedulerListItemDetails(SchedulerListItem item, Form owner)
{
InitializeComponent();
this.SourcePath = item.SourcePath;
this.DestinationPath = item.DestinationPath;
this.OldFormat = item.OldFormat;
this.ExportToExcel = item.ExportToExcel;
this.owner = owner;
this.underlyingItem = item;
}
public SchedulerListItemDetails()
{
InitializeComponent();
}
private Form owner = null;
private SchedulerListItem underlyingItem;
public Boolean ExportToExcel
{
get
{
return this.cbxExcel.Checked;
}
set
{
this.cbxExcel.Checked = value;
}
}
public Boolean OldFormat
{
get
{
return this.cbxOldFormat.Checked;
}
set
{
this.cbxOldFormat.Checked = value;
}
}
public String DestinationPath
{
get
{
return this.tbxDestinationPath.Text;
}
set
{
this.tbxDestinationPath.Text = value;
}
}
public String SourcePath
{
get
{
return this.tbxSourcePath.Text;
}
set
{
this.tbxSourcePath.Text = value;
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.owner.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
underlyingItem.SourcePath = this.SourcePath;
underlyingItem.DestinationPath = this.DestinationPath;
underlyingItem.OldFormat = this.OldFormat;
underlyingItem.ExportToExcel = this.ExportToExcel;
btnCancel_Click(sender, e);
}
}
I'll make an answer, because it should help you to solve your problem.
You have default (parameterless) constructor, which may be called and if it is called, then your constructor with parameters is not called.
Proper design would be something like
public partial class SchedulerListItemDetails : UserControl
{
public SchedulerListItemDetails()
{
InitializeComponent();
}
public SchedulerListItemDetails(SchedulerListItem item, Form owner): this()
{
this.SourcePath = item.SourcePath;
...
}
}
Notice this(), this ensure what parameterless constructor is called before (and InitializeComponent() as well, no need to duplicate it in another constructor).
Back to your problem. In your case it's like this
public partial class SchedulerListItemDetails : UserControl
{
public SchedulerListItemDetails()
{
InitializeComponent();
}
public SchedulerListItemDetails(SchedulerListItem item, Form owner)
{
InitializeComponent();
this.SourcePath = item.SourcePath;
...
}
}
Only one constructor can be called. So if you put breakpoint in parameterless one and it's triggered, then you have problems. Because you create somewhere SchedulerListItemDetails without setting it's properties (they stay default).
More likely problem is that you create new instance of that object (either before or after constructing proper, if your code ever construct such object) and that instance is what you inspect later.
So after i got a quick course of how win forms work i figured out what the problem was.
my code that i thought was enough is:
public FrmSchedulerItemDetails(SchedulerListItem item)
{
InitializeComponent();
this.DetailsControl = new SchedulerListItemDetails(item, this);
}
public SchedulerListItemDetails DetailsControl
{
get
{
return this.detailsControl;
}
set
{
this.detailsControl = value;
}
}
the this.detailsControl is the control im trying to setup, but as i have learned the correct way of replacing a component for a new one is:
public FrmSchedulerItemDetails(SchedulerListItem item)
{
InitializeComponent();
this.DetailsControl = new SchedulerListItemDetails(item, this);
}
public SchedulerListItemDetails DetailsControl
{
get
{
return this.detailsControl;
}
set
{
this.Controls.Remove(this.detailsControl);
this.detailsControl = value;
this.Controls.Add(this.detailsControl);
}
}
Feel kinda silly now :).
I am trying to create a custom component. The component should by dynamically initialized in code behind. The component presents a custom Window containing other components, like datefields, dropdown fields etc. I derived my class from Ext.Net.Window and added simple DateField. The date should than be used by a button click on the server (Date should not be passed over DirectMethod parameter). When I add this component to mark-up it works perfectly. But when I add the window in code behind, the value of the datefield is not set after the server call.
I am creating the window in the life cycle in OnInit event by "Controls.Add(mywindow)". It would be great if anybody could give me a hint. Here my window code (onExecuteButtonClick just calls the direct method and hides the window):
public sealed class WindowFilterComponent:Window
{
private const string Script = "MyProject.JavaScript.src.WindowFilterComponent.js";
public override string InstanceOf
{
get
{
return "MyProject.Filter.WindowFilterComponent";
}
}
public override string XType
{
get
{
return "windowfiltercomponent";
}
}
private Button _btnExecute;
private Button _btnCancel;
private DateField _dateField;
protected override void OnInit(EventArgs e)
{
AutoHeight = true;
_btnExecute = new Button("Execute Export");
_btnExecute.Listeners.Click.Handler = string.Format("#{{{0}}}.onExecuteButtonClick()", ID);
_btnCancel = new Button("Cancel");
_btnCancel.Listeners.Click.Handler = string.Format("#{{{0}}}.onCancelButtonClick()", ID);
Buttons.Add(_btnExecute);
Buttons.Add(_btnCancel);
_dateField = new DateField();
Items.Add(_dateField);
base.OnInit(e);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (ExtNet.IsAjaxRequest || Page.IsCallback) return;
ResourceManager.GetInstance().AddDirectMethodControl(this);
}
[DirectMethod(ShowMask = true)]
public void ExecuteClick()
{
var date = _dateField.SelectedValue;
}
}
Now the useage in my page in the OnInit event:
protected override void OnInit(EventArgs e)
{
var myWindow = new WindowFilterComponent()
{
Hidden = false,
Width = 500
};
myWindow.ID = myWindow.ID + "MyComponent";
Controls.Add(myWindow);
base.OnInit(e);
}
I think the Window is rendered outside of the Form.
Please replace
Controls.Add(myWindow);
with
Form.Controls.Add(myWindow);
Also I would recommend to set up explicit IDs for the submittable fields (the DateField in your case) to ensure that the id key from POST data will match the control's ID on the server.
Is there any way to hide the arrow on a ToolStripMenuItem? The arrow is enclosed in the red square.
I've found this is very helpful, you can create your own custom ToolStripRenderer inherits from ToolStripProfessionalRenderer, like this:
public class CustomToolStripRenderer : ToolStripProfessionalRenderer
{
protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e)
{
e.ArrowRectangle = Rectangle.Empty;//Don't draw arrow
base.OnRenderArrow(e);
}
}
//and update the Renderer property of your MenuStrip
menuStrip1.Renderer = new CustomToolStripRenderer();
UPDATE
For your requirement, there are some ways to do but I think this is a good way:
public class CustomToolStripRenderer : ToolStripProfessionalRenderer
{
protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e)
{
if (RenderArrow != null) RenderArrow(this, e);
base.OnRenderArrow(e);
}
public new event ToolStripArrowRenderEventHandler RenderArrow;//This will hide the default RenderArrow event which can't help you change the e argument because the default is fired after the Arrow is rendered.
}
//Now you have to create your own List<ToolStripItem> to contain all the items whose arrows should not be rendered
List<ToolStripItem> ItemsWithoutArrow = new List<ToolStripItem>();
//Add a method to add an item to that list
private void SuppressDrawArrow(ToolStripItem item)
{
if (!ItemsWithoutArrow.Contains(item)) ItemsWithoutArrow.Add(item);
}
//Assign custom ToolStripRenderer for your MenuStrip
menuStrip1.Renderer = new CustomToolStripRenderer();
//Now add a RenderArrow event handler, this RenderArrow event is the new we created in the class CustomToolStripRenderer
((CustomToolStripRenderer)menuStrip1.Renderer).RenderArrow += (s, e) =>
{
if(ItemsWithoutArrow.Contains(e.Item)) e.ArrowRectangle = Rectangle.Empty;
};
//Add some item to the ItemsWithoutArrow to test
SuppressDrawArrow(item1ToolStripMenuItem);
Another solution (I like many solutions to a problem :)
public class CustomToolStripRenderer : ToolStripProfessionalRenderer
{
protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e)
{
if(!itemsWithoutArrow.Contains(e.Item)) base.OnRenderArrow(e);
}
public void SuppressDrawArrow(ToolStripItem item){
if (!itemsWithoutArrow.Contains(item)) itemsWithoutArrow.Add(item);
}
public void AllowDrawArrow(ToolStripItem item){
itemsWithoutArrow.Remove(item);
}
private List<ToolStripItem> itemsWithoutArrow = new List<ToolStripItem>();
}
//Use in code
CustomToolStripRenderer renderer = new CustomToolStripRenderer();
renderer.SuppressDrawArrow(item1ToolStripMenuItem);
menuStrip1.Renderer = renderer;
//This solution fits your requirement (draw or don't draw arrow) but if you also want to change such as ArrowColor, the previous solution would be better.
I've found that we can render it freely with many options. That's great :)
My asp.net application has a custom base user control that is inherited from other user controls. This custom base user control has three properties that have been made public. When the user control is loaded the custom base user control properties are null. I am trying to figure what I am doing wrong. can someone please help figure out what step I am missing?
custom base user control loading code from parent page:
private void Render_Modules()
{
foreach (OnlineSystemPageCustom.OnlineSystemPageHdr.OnlineSystemPageModule item in custompage.Header.Modules)
{
if (item.ModuleCustomOrder != 99)
{
webonlinecustombase ctl = (webonlinecustombase)Page.LoadControl("../IPAM_Controls/webtemplatecontrols/webonlinecustombase.ascx");
ctl.Event = Event;
ctl.custompage = custompage;
ctl.custommodule = item;
this.eventprogrammodules.Controls.Add(ctl);
}
}
}
custom base user control code behind
public partial class webonlinecustombase : System.Web.UI.UserControl
{
public Event Event { get; set; }
public OnlineSystemPageCustom custompage { get; set; }
public OnlineSystemPageCustom.OnlineSystemPageHdr.OnlineSystemPageModule custommodule { get; set; }
public void Page_Load(object sender, EventArgs e)
{
string typeName = custommodule.ModuleInternetFile;
inpagelink.HRef = "#" + custommodule.ModuleName.Replace(" ", "").Replace("/", "");
modtitle.InnerText = custommodule.ModuleName;
Type child = Type.GetType(typeName);
UserControl ctl = (UserControl)Page.LoadControl(child, null);
if (ctl != null)
{
this.modsection.Controls.Add(ctl);
}
}
}
sample code of user control inheriting base user control
public partial class eventscientificoverview : webonlinecustombase
{
protected void Page_Load(object sender, EventArgs e)
{
if (custommodule.ModuleDefaultVerbiage != null && custommodule.ModuleDefaultVerbiage != "") { this.Load_Verbiage(false); }
else if (custommodule.ModuleCustomVerbiage != null && custommodule.ModuleCustomVerbiage != "") { this.Load_Verbiage(true); }
}
protected void Load_Verbiage(bool usecustom)
{
if (usecustom) { this.scientificoverviewverbiage.InnerHtml = custommodule.ModuleCustomVerbiage; }
else { this.scientificoverviewverbiage.InnerHtml = custommodule.ModuleDefaultVerbiage; }
}
}
You must call Render_Modules in the init event of the parent page.
Also, you may want to restructure your base/custom classes to avoid event execution order confusion since the load event will be fired in both the base and the custom classes.
Any time we have this type of structure, we always implement an OnLoad method in the base class for inheritors to override. This way we can control exactly when the Load logic is executed in the inheritors.
Updated with additional info
Here is some additional information on how to handle the load events in base and child classes.
In webonlinecustombase, add the following:
protected virtual void OnPageLoad() {
}
then modify your page load event to call this new method at the appropriate time:
public void Page_Load(object sender, EventArgs e)
{
string typeName = custommodule.ModuleInternetFile;
inpagelink.HRef = "#" + custommodule.ModuleName.Replace(" ", "").Replace("/", "");
modtitle.InnerText = custommodule.ModuleName;
Type child = Type.GetType(typeName);
UserControl ctl = (UserControl)Page.LoadControl(child, null);
if (ctl != null)
{
this.modsection.Controls.Add(ctl);
}
// Now let the inheritors execute their code
OnPageLoad();
}
then, in your inherited class, change:
protected void Page_Load(object sender, EventArgs e)
to
protected override void OnPageLoad()
As I was reviewing this code, I discovered that you are also dynamically loading controls in webonlinecustombase. You will need to move the loading of the controls into the init event in order for them to work correctly in the standard page logic.
Did you try base.[PropertyName] ?
If you have a new keyword or override in your derived class and had only the values in your base class could be the culprit. This has happened to me before.