I have been wondering, what would be the better way to implement Locking/Disabling a bunch of Ribbon UI controls by just a click?
Currently, my approach is kinda simple and basic:
private void tbtnLock_Click(object sender, RibbonControlEventArgs e)
{
if (tbtnLock.Checked)
{
control1.Enabled = false;
control2.Enabled = false;
control3.Enabled = false;
//...
//controlN.Enabled = false;
}
else
{
control1.Enabled = true;
control2.Enabled = true;
control3.Enabled = true;
//...
//controlN.Enabled = true;
}
}
I think it's okay if we only have just a few controls but once we add more and more controls onto the Ribbon bar, I don't think it'd be a good coding practice to do things like above.
Is there any cleaner and neater approach to this? Am I able to get the collection of all the controls on the Ribbon bar? Hopefully someone can give me some pointers here? Thanks very much.
EDIT:
Revised code below:
private void tbtnLock_Click(object sender, RibbonControlEventArgs e)
{
toggleUILockState();
}
private void toggleUILockState()
{
if (group1.Items != null)
{
foreach (RibbonControl c in group1.Items)
{
if (c.Name != "tbtnLock")
{
c.Enabled = !tbtnLock.Checked;
}
}
}
}
I think it looks a lot better than the previous version. Thanks everyone for the help.
Well certainly the first step to improve the code would be to remove the if statement and assigned the enabled state of the control directly with the checked state of the tbtnLock control like...
control1.Enabled = !tbtnLock.Checked;
control2.Enabled = !tbtnLock.Checked;
that would cut your code if half straight away. You may want to assign that to a bool first incase you want to do additional processing on it later (maybe some other object helps determining lock state for example)
bool isEnabled = !tbtnLock.Checked;
control1.Enabled = isEnabled;
control2.Enabled = isEnabled;
Further than that I would need to know what "ribbon" control you are using. Do you have a link?
But as you have hinted, I would want to look at trying to find a colleciton of controls, loop through them, check if the control is not the tbtnLock control and disable/enable as needed.
Also, I would recommend move all this code to a function outside of the event handle, in case you need to call this method from other code. Something like...
private void tbtnLock_Click(object sender, RibbonControlEventArgs e)
{
UpdateRibbonState();
}
private void UpdateRibbonState(){
//Code goes here
}
EDIT: Making assumtion that a "group" (as described in comments) has a collection of controls...
foreach(Control c in group.Controls)
{
if(c.Name != "tbtnLock")
{
c.Enabled = !tbtnLock.Checked;
}
}
I am not familiar with any built-in .Net ribbon controls and as there is no link to a 3rd party set) I am making a best guess at the properties available for a "group"