Tuesday, June 23, 2009

Remove Focus from a Separator and MenuItem in wpf

This post is related to the problem i had reported in my article related to WPF Menus. A bound MenuItem associated with a command, if disabled (CanExecute of ICommand checks whether a command can be Invoked or not. If cannot be invoked, it'll disable the control, in our case should disable the MenuItem) or a Separator should not be a Focusable item. But instead what i could notice was that both the controls were actually looking like available for selection even if disabled.

Still i'm not able to conclusively say what the reason for the problem is but atleast i have a workaround. Also somewhere i read that it's not a good practice if we use an Item control in a DataTemplate. So the workaround was based on a brilliant article by Bea Stollnitz which explained about using a StyleSelector class to choose a style for a DataType passed.

Taking help from the same article, i modified my code to get the style specific to a Separator and also for a MenuItem.

For the functionality to work, i created a a CustomStyleSelector class which inherits from the StyleSelector class. So the binding to this class will be like
public class CustomStyleSelector : StyleSelector
{
public override Style SelectStyle(object item, DependencyObject container)
{
if (item is SeparatorViewModel)
{
return (Style ((FrameworkElement)container).FindResource("separatorStyle");
}
if(item is MenuItemViewModel)
{
return (Style ((FrameworkElement)container).FindResource("menuStyle");
}
return null;
}
}
The thing to notice here is that the "menuStyle" needs to have two parts, say when it's an
enabled item let us have a style called "EnabledMenuStyle" which will have MenuItem property "StaysOpenOnClick="false". Similarly if the MenuItem is a disabled one (We are not setting the IsEnabled="false" or anything but the commands does it for us) let's have a Style called "disabledMenuStyle" for which "StaysOpenOnClick="true". So these styles will actually enable us to do the workaround required.

The complete code along with the article will be available for download from codeproject pretty soon.

No comments: