I am trying to optimize my code a bit by either using delegates or using a class instance as parameter. I am pretty new to C# and I am not yet sure which one is the better approach assuming im on the right track in the first place. But my problem relates to sending a class instance as parameter. Let me explain. I am trying to follow this logic but im failiing....
I have created a VSTO Ribbon with a few buttons. It looks somewhat like this:
Now, I am now trying to add some functionality to the buttons, so a click on each button opens a new TaskPane.
I wrote this code for the Calendar
Ribbon button which sits in the GSMRibbon.cs
note: I think that for the more experienced programmers this code will be quite easy to understand but in case you guys dont understand something please let me know in the comments i will explain ).
namespace GSM
{
public partial class GSMRibbon
{
private void GSMRibbon_Load(object sender, RibbonUIEventArgs
{
}
private CustomTaskPane taskPane;
private CustomTaskPane TaskPane
{
get
{
return this.taskPane;
}
}
private void vendors_calendar_Click(object sender, RibbonControlEventArgs e)
{
string newTitle = "PO Calendar";
if (TaskPane != null)
{
if (TaskPane.Title != newTitle)
{
Globals.ThisAddIn.CustomTaskPanes.Remove(TaskPane);
CreateTaskPane(newTitle);
}
else
{
taskPane.Visible = true;
}
}
else
{
CreateTaskPane(newTitle);
}
}
private void CreateTaskPane(string title)
{
var taskPaneView = new CalendarView();
taskPane = Globals.ThisAddIn.CustomTaskPanes.Add(taskPaneView, title);
taskPane.Visible = true;
}
}
}
Ok. What I wanted to do was to modify the CreateTaskPane function adding a class
parameter (does this make sense?) so I can re-use this function multiple times for different buttons on the ribbon. I have created a separate View
for each of the buttons, but I am not sure how to pass the View
.
So, im after something like this: (CalendarView is the name of the View)
CreateTaskPane(new CalendarView(), newTitle);
and the function something like:
private void CreateTaskPane(object typeOfView, string title)
{
var taskPaneView = new (typeOfView)Object;
taskPane = Globals.ThisAddIn.CustomTaskPanes.Add(taskPaneView, title);
taskPane.Visible = true;
}
I really hope you understand what I am trying to but being unable to do myself. I appreciate any attempt to help. Thanks
You can use generics to do this:
private void CreateTaskPane<T>(string title) where T : UserControl, new()
{
T taskPaneView = new T();
taskPane = Globals.ThisAddIn.CustomTaskPanes.Add(taskPaneView, title);
taskPane.Visible = true;
}
You would then call it via:
CreateTaskPane<CalendarView>(newTitle);
Alternatively, you could write this as:
private void CreateTaskPane<T>(T taskPaneView, string title) where T : UserControl
{
taskPane = Globals.ThisAddIn.CustomTaskPanes.Add(taskPaneView, title);
taskPane.Visible = true;
}
Then call via:
CreateTaskPane(new CalendarView(), newTitle);