【发布时间】:2014-12-15 10:02:20
【问题描述】:
我对弹出窗口的关闭行为感到困惑。一直在搜索论坛,但找不到适合我情况的答案。 我有一个 ListView 和一个用于 ListView 的弹出窗口。单击 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>
我的 VM 中的代码如下所示:
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;
}
}
}
}
就是这样。现在,当我运行这个示例应用程序时,弹出窗口会按预期打开,但只有在整个窗口失去焦点时才会关闭。但是当我单击 ListView 之外的某个位置时,它也应该关闭。
有什么想法吗?
【问题讨论】:
-
我在您的代码中看不到任何将
PopupOpen设置为false的执行路径。 -
它应该会自动关闭。 MSDN:当 StaysOpen 为 false 时,Popup 控件会拦截所有鼠标和键盘事件,以确定这些事件之一何时在 Popup 控件之外发生。
-
@CrazyChief 你搞错了:public class MyVM, Public MainWindow()(看起来像错误的构造函数)
-
@Moti:PoupOpen 默认设置为 false。
-
@deafjeff:应该但它没有;)复制并粘贴我的代码并尝试一下。关于构造函数:更新了我上面的代码示例。是复制和粘贴错误。在我的项目中是正确的。