1

是否有替代的 ItemsControl(与 ListBox 非常相似),或者在“再次”选择最后一个选定对象时引发的 ListBox 中的事件?由于某些要求,我不能使用代码隐藏,因此解决方案必须仅在 XAML 中。:(

4

2 回答 2

0

当触发 mouseclick 事件时,您可能会尝试使用 Blend SDK 行为 InvokeMethod 在 ViewModel 上执行方法。

本文是关于 Silverlight,但讨论了可在 WPF 中使用的相同行为

于 2012-05-04T05:43:01.177 回答
0

我无法仅使用 XAML 来实现整个事情 :(。但我使用鼠标单击事件来实现它。(感谢用户的建议)。答案可能并不完美,但考虑分享它,因为它可能对其他人有所帮助。

public class CustomListBox : ListBox
{
    private SelectionChangedEventArgs cachedArgs;
    private int state;

    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);
        this.AddHandler(Mouse.MouseDownEvent, new MouseButtonEventHandler(CustomListBox_MouseDown), true);
        state = 0;
    }

    void CustomListBox_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (state == 1) // I don't want to re-raise event if ListBox had raised it already. 
        {
            this.OnSelectionChanged(cachedArgs);
        }
        state = 3;
    }

    protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
    {
        state = 1;
        base.OnPreviewMouseLeftButtonDown(e);
    }

    /// <summary>
    /// Responds to a list box selection change by raising a <see cref="E:System.Windows.Controls.Primitives.Selector.SelectionChanged"/> event.
    /// </summary>
    /// <param name="e">Provides data for <see cref="T:System.Windows.Controls.SelectionChangedEventArgs"/>.</param>
    protected override void OnSelectionChanged(SelectionChangedEventArgs e)
    {
        cachedArgs = e;
        state = 2;
        base.OnSelectionChanged(e);
        foreach (var item in e.AddedItems)
        {
            Debug.WriteLine(item);
        }
    }
}

I have used three different states. PreviewMouseLeftButtonDown event is raised always before other two events, so state 1. If there is a SelectionChanged event raised, it will be before Mouse.MouseDownEvent so state 2 and 3 respectively.

于 2012-05-10T16:02:44.447 回答