Поведение ListBoxItem
может быть расширено путем реализации пользовательского присоединенного поведения: добавьте аспект выбора правой кнопки.Дополнительная информация о прикрепленном поведении: Введение в присоединенное поведение в WPF .
public static class ListBoxItemBehavior
{
#region IsEnabled
public static bool GetIsEnabled(ListBoxItem listBoxItem)
{
return (bool)listBoxItem.GetValue(IsEnabledProperty);
}
public static void SetIsEnabled(ListBoxItem listBoxItem, bool value)
{
listBoxItem.SetValue(IsEnabledProperty, value);
}
public static readonly DependencyProperty IsEnabledProperty =
DependencyProperty.RegisterAttached(
"IsEnabled",
typeof(bool),
typeof(ListBoxItemBehavior),
new UIPropertyMetadata(false, OnIsEnabledChanged));
static void OnIsEnabledChanged(
DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
ListBoxItem item = depObj as ListBoxItem;
if (item == null)
return;
if (e.NewValue is bool == false)
return;
if ((bool)e.NewValue)
item.MouseRightButtonDown += ItemOnMouseRightButtonDown;
else
item.MouseRightButtonDown -= ItemOnMouseRightButtonDown;
}
private static void ItemOnMouseRightButtonDown(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
ListBoxItem item = mouseButtonEventArgs.OriginalSource as ListBoxItem;
if (item != null)
{
item.IsSelected = !item.IsSelected;
}
}
#endregion
}
Использование (XAML): присоединенное поведение должно применяться для ListBoxItem
с ListBox
.
Пожалуйста, замените BEHAVIOR_NAMESPACE на полное имя пространства имен, в котором определен класс ListBoxItemBehavior
.
<Window ...
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Behaviors="clr-namespace:BEHAVIOR_NAMESPACE">
<ListBox ...
SelectionMode="Multiple">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Behaviors:ListBoxItemBehavior.IsEnabled" Value="True" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Window>
Надеюсь, это поможет.