private static object CoerceSelectedItem(DependencyObject d, object value)
{
RibbonGallery gallery = (RibbonGallery)d;
if (!gallery.IsSelectionChangeActive)
{
object oldItem = gallery.SelectedItem;
object newItem = value;
if (!VerifyEqual(oldItem, newItem))
{
if (newItem != null)
{
RibbonGalleryCategory category = null;
RibbonGalleryItem galleryItem = null;
// If the newItem doesn't exist in RibbonGallery under any category then return UnsetValue
// so as not to change existing value
bool ignoreItemContainerGeneratorStatus = false;
if (!gallery.ContainsItem(newItem, ignoreItemContainerGeneratorStatus, out category, out galleryItem))
{
return DependencyProperty.UnsetValue;
}
// Changes the selection to newItem
gallery.ChangeSelection(newItem, galleryItem, true);
}
else
{
// Deselect oldItem
gallery.ChangeSelection(oldItem, null, false);
}
}
else if (gallery.ShouldForceCoerceSelectedItem)
{
RibbonGalleryCategory category = null;
RibbonGalleryItem galleryItem = null;
// This block is called when ItemCollection changes either at the Gallery or the Category levels
// to handle the case that a previously SelectedItem is removed or replaced.
bool ignoreItemContainerGeneratorStatus = true;
if (!gallery.ContainsItem(newItem, ignoreItemContainerGeneratorStatus, out category, out galleryItem))
{
// Deselect oldItem
value = null;
gallery.ChangeSelection(oldItem, null, false);
}
}
}
return value;
}