ListView的弹出窗口和StaysOpen =" False"不正常

时间:2014-12-15 10:02:20

标签: c# wpf listview popup

我坚持使用Popup的结束行为。一直在搜索论坛,但无法找到适合我的情况的答案。 我有一个ListView和一个用于ListView的Popup。单击ListViewItem时应打开Popup,单击其他内容(ListViewItem除外)时应关闭Popup。我正在使用MVVM,因此我将Popup的IsOpen-Property绑定到我的VM中的属性,该属性在绑定到ListView的SelectedItemProperty的属性中设置。 代码看起来像这样: MainWindow.xaml

<Grid>
    <ListView Name="List" ItemsSource="{Binding MyList}" SelectedItem="{Binding MyItem}" HorizontalAlignment="Left" />
     <Popup IsOpen="{Binding PopupOpen}" Placement="Right" StaysOpen="False" PlacementTarget="{Binding ElementName=List}">
        <TextBlock Text="I'm a Popup" />
    </Popup>
</Grid>

我的虚拟机中的代码如下:

public class MyVM
{
    private string myItem;
    private bool popupOpen;

    public MyVM()
    {
        this.MyList = new List<string> { "Item 1", "Item 2", "Item 3" };            
    }

    public List<string> MyList { get; set; }

    public bool PopupOpen
    {
        get
        {
            return this.popupOpen;
        }
        set
        {
            this.popupOpen = value;
            this.OnPropertyChanged();
        }
    }

    public string MyItem
    {
        get
        {
            return this.myItem;
        }

        set
        {
            this.myItem = value;
            this.OnPropertyChanged();

            if (value != null)
            {
                this.PopupOpen = true;
            }
        }
    }
}

这就是全部。现在,当我运行此示例应用程序时,Popup按预期打开,但仅在整个窗口失去焦点时关闭。但是当我点击ListView之外的某个地方时它也应该关闭。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我尝试了像MouseCapturing一样出现在脑海中的所有内容,在Popup中播放元素的焦点,从各种事件(如ListItem的PreviewMouseDown,PreviewMouseUp)打开Popup但是无法获得StaysOpen功能正常。我没有想法,所以我自己实现了所需的StaysOpen功能:

为此,我注册了MainWindow的PreviewMouseLeftButtonDown,并在那里处理弹出窗口的关闭,即在窗口上单击时关闭所有弹出窗口。为了避免在弹出窗口内部时弹出窗口被关闭,我将相同的处理程序添加到弹出窗口并将“IsOpen”-Property设置回“true”。 丑陋但它有效。

因此,如果有人有更好的想法或能够启发我关于StaysOpen-Property如何真正起作用的内部功能,我会很高兴;)

相关问题