listBox的selectionchanged事件的替代方案

时间:2012-05-04 04:28:56

标签: wpf xaml

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

2 个答案:

答案 0 :(得分:0)

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

This article is about Silverlight但讨论了可在WPF中使用的相同行为

答案 1 :(得分:0)

我无法使用XAML实现整个事情:(但我使用鼠标点击事件来实现它。(感谢user的建议。)答案可能不完美,但想分享它因为它可以帮助别人。

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);
        }
    }
}

我使用了三种不同的状态。 PreviewMouseLeftButtonDown事件总是在其他两个事件之前引发,因此状态1.如果引发了SelectionChanged事件,它将在Mouse.MouseDownEvent之前分别为状态2和3。