How can I get a Click event in a ListBoxItem?

Is there any way to implement Clickon ListBoxItem? Exists MouseLeftButtonUp, but it’s actually not the same, I can pull it to another place and drag it to another ListBoxItem, and it still works, a little tho problem, maybe this is strange for tho users

+3
source share
2 answers

Can you create a new ControlTemplate for ListBoxItem with something clickable as the root element (like Button), handle the click-event event and place the ContentPresenter inside the "clickable"?

+2
source

, , , , , - , ListBoxItem .

Click ListBoxItem, . ListBoxItem MouseEnter, MouseLeave, MouseUp, MouseDown, , .

public class ClickableListBoxItem : ListBoxItem
{
    // Register the routed event
    public static readonly RoutedEvent ClickEvent = 
        EventManager.RegisterRoutedEvent( "Click", RoutingStrategy.Bubble, 
        typeof(RoutedEventHandler), typeof(ClickableListBoxItem));

    // .NET wrapper
    public event RoutedEventHandler Click
    {
        add
        {
            AddHandler(ClickEvent, value);
        } 
        remove
        {
            RemoveHandler(ClickEvent, value);
        }
    }

    protected void OnClick()
    {
        RaiseEvent(new RoutedEventArgs(ClickEvent));
    }

    private bool m_isClickable = false;
    private bool m_click = false;
    protected override void OnMouseEnter(System.Windows.Input.MouseEventArgs e)
    {
        m_isClickable = true;
        base.OnMouseEnter(e);
    }
    protected override void OnMouseLeave(System.Windows.Input.MouseEventArgs e)
    {
        m_isClickable = false;
        base.OnMouseLeave(e);
    }
    protected override void OnPreviewMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e)
    {
        if (m_click == true)
        {
            OnClick();
        }
        base.OnPreviewMouseLeftButtonUp(e);
    }
    protected override void OnPreviewMouseLeftButtonDown(System.Windows.Input.MouseButtonEventArgs e)
    {
        if (m_isClickable == true)
        {
            m_click = true;
        }
        base.OnPreviewMouseLeftButtonDown(e);
    }
}

ListBox ClickableListBoxItem ListBoxItem, ListBox GetContainerForItemOverride.

public class ClickableListBox : ListBox
{
    protected override DependencyObject GetContainerForItemOverride() 
    {
        //Use our own ListBoxItem 
        return new ClickableListBoxItem(); 
    }
}

ClickableListBox Xaml Click . , ItemTemplate, Buttons, TextBoxes, TextBlocks ..

<local:ClickableListBox x:Name="c_listBox">
    <local:ClickableListBox.ItemContainerStyle>
        <Style TargetType="{x:Type local:ClickableListBoxItem}">
            <EventSetter Event="Click" Handler="ListBoxItem_Click"/>
        </Style>
    </local:ClickableListBox.ItemContainerStyle>
</local:ClickableListBox>

ItemTemplate ListBoxItem .

+3

Source: https://habr.com/ru/post/1774240/


All Articles