
I can define a class (let's call it "MyCtg") which derives from ContextualTabGroup, and bind its IsActive property to a dependency property in my view model. For example, I can bind it to a Boolean property called "IsCorrectDocType" like this: IsActive="{Binding IsCorrectDocType}"
I create an instance of this class and add it to the ribbon's ContextualTabGroups collection in code like this:
var myCtg = new MyCtg();
ribbon.ContextualTabGroups.Add(myCtg);
I get different behavior depending on whether the "IsCorrectDocType" property (i.e. the property that IsActive is bound to) is "True" or "False" at the time the object is added to the collection.
If "IsCorrectDocType" is "False" at the time I add the group to the collection, everything works correctly and the tab group appears and disappears as expected when I toggle "IsCorrectDocType" true and false.
However, if "IsCorrectDocType" is "True" at the time that I attempt to add the instance of the class to the ContextualTabGroups collection, I get the following exception:
InvalidOperationException was unhandled: Cannot change ObservableCollection during a CollectionChanged event.
The only way that I found to avoid this problem is to:
- Use BindingOperations.GetBinding to retrieve the IsActiveProperty's binding. If the binding is null, IsActive is not databound, and we can simply add the object to the ContextualTabGroups collection.
- Manually set the IsActive flag to its current state [i.e. myCtg.IsActive = myCtg.IsActive;], having the effect of removing the binding. It also works to set IsActive explicitly to either true or false.
- Add my ContextualTabGroup object to the ribbon's ContextualTabGroups collection.
- Restore the IsActiveProperty's binding using BindingOperations.SetBinding.
My Contextual Tab Group is very simple:
<ribbon:ContextualTabGroup x:Class="ActiproPlayground.MyCtg"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ribbon="http://schemas.actiprosoftware.com/winfx/xaml/ribbon"
Label="Contextual Tools"
IsActive="{Binding IsCorrectDocType}"
>
<ribbon:Tab Label="XSD">
<ribbon:Group Label="Demo">
<ribbon:Button ImageSourceLarge="/Resources/Images/CloseTab32.png" Label="Close Contextual Tab" />
</ribbon:Group>
</ribbon:Tab>
</ribbon:ContextualTabGroup>
And my view model is just as basic:
using System.Windows;
namespace ActiproPlayground
{
public class MainWindowViewModel : DependencyObject
{
public bool IsCorrectDocType
{
get { return (bool)GetValue(IsCorrectDocTypeProperty); }
set { SetValue(IsCorrectDocTypeProperty, value); }
}
public static readonly DependencyProperty IsCorrectDocTypeProperty = DependencyProperty.Register("IsCorrectDocType", typeof(bool), typeof(MainWindowViewModel));
}
}
[Modified 12 years ago]