private static object CoerceSelectedValue(DependencyObject d, object value)
{
RibbonGallery gallery = (RibbonGallery)d;
if (!gallery.IsSelectionChangeActive)
{
object oldValue = gallery.SelectedValue;
object newValue = value;
if (!VerifyEqual(oldValue, newValue))
{
if (newValue != null)
{
object newItem;
RibbonGalleryCategory category = null;
RibbonGalleryItem galleryItem = null;
// If the newValue doesn't exist in RibbonGallery under any category then return UnsetValue
// so as not to change existing value
bool ignoreItemContainerGeneratorStatus = false;
if (!gallery.ContainsValue(value, ignoreItemContainerGeneratorStatus, out newItem, out category, out galleryItem))
{
return DependencyProperty.UnsetValue;
}
// Changes the selection to newItem
gallery.SelectedItem = newItem;
}
else
{
// Deselect
gallery.SelectedItem = null;
}
}
else if (gallery.ShouldForceCoerceSelectedValue)
{
object newItem;
RibbonGalleryCategory category = null;
RibbonGalleryItem galleryItem = null;
// This block is called when generating RibbonGalleryCategory containers
// to synchronize the SelectedItem with the previously specified SelectedValue.
// If a match isn't found yet we keep the oldValue as is by returning UnsetValue.
bool ignoreItemContainerGeneratorStatus = true;
if (!gallery.ContainsValue(value, ignoreItemContainerGeneratorStatus, out newItem, out category, out galleryItem))
{
return DependencyProperty.UnsetValue;
}
gallery.SelectedItem = newItem;
}
}
return value;
}