我找到了解决办法。基本上,我创建了一个附加属性,在任何
Selector
(包括
ListBox
Canvas.ZIndex
根据容器是否表示所选项目:
public static readonly DependencyProperty SetZIndexOnSelectionProperty = DependencyProperty.RegisterAttached(
"SetZIndexOnSelection", typeof(bool), typeof(FrameworkUtils),
new PropertyMetadata(zIndexSettingChanged));
public static bool GetSetZIndexOnSelection(DependencyObject obj)
{
return (bool)obj.GetValue(SetZIndexOnSelectionProperty);
}
public static void SetSetZIndexOnSelection(
DependencyObject obj, bool value)
{
obj.SetValue(SetZIndexOnSelectionProperty, value);
}
private static void zIndexSettingChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
if (obj is Selector)
{
var selector = obj as Selector;
selector.SelectionChanged += (s, e) =>
{
if (selector.SelectedItem != null)
{
foreach (var pair in selector.GetItemsAndContainers())
{
pair.Value.SetValue(
Canvas.ZIndexProperty,
(pair.Key == selector.SelectedItem) ? 1 : 0);
}
}
};
}
}