Solution: Toggling IsEnabled doesn't work as expected with ContextMenu Item in Silverlight 5 control toolkit


One of the issue with ContextMenu control in Silverlight 5 or 4 control toolkit is that when you toggle IsEnabled property for a ContextMenu Item at runtime the visual behaviour doesnt change.

1) Have a context menu that shows an item as disabled.

2) Bring up the context menu via right-click, you'll see the item disabled

3) Then change the status of the menu item to be disabled by setting IsEnabled property to true.

4) Bring up the contextmenu again it will still show enabled and you mouse over it then it will change to enabled status.

5) Similar thing happens when you change from Enabled to Disabled.


Solution 1: 

Simply change the VisualState of the MenuItem explicitly by using VisualStateManager.


menuItem.IsEnabled = false;
VisualStateManager.GoToState(menuItem, "Disabled", true);

------

menuItem.IsEnabled = true;
VisualStateManager.GoToState(menuItem, "Normal", true);


Solution 2: Update the control toolkit code with a patch fix

1) Go to the source code of control toolkit (System.Windows.Controls.Input.Toolkit) present in C:\Program Files\Microsoft SDKs\Silverlight\v5.0\Source

2) Open the .csproj in Visual Studio 2010

3) Edit file ContextMenu/MenuItem.cs to add the below patch at line number 143.

IsEnabledChanged = new DependencyPropertyChangedEventHandler(HandleIsEnabledChanged);


Code looks like: 

public MenuItem()
{
  DefaultStyleKey = typeof(MenuItem);
  IsEnabledChanged = new DependencyPropertyChangedEventHandler(HandleIsEnabledChanged);
  UpdateIsEnabled();
}