[英]How to prevent Popup losing focus?
我有一個Combobox
在一個數據模板中定義ItemsControl.
此ComboBox
具有定義的Button
。 在Button_Click
事件上,應顯示一個Popup
Button_Click
。 此Popup
包含一個自定義UserControl
,其中定義了一些控件。
這是解釋我的問題之前的代碼:
<ComboBox x:Name="cb" HorizontalAlignment="Center" Grid.Column="2" Width="140" Visibility="{Binding HasCombobox, Converter={StaticResource BoolToVis}}">
<ComboBox.ItemsSource>
<CompositeCollection>
<CollectionContainer Collection="{Binding Source={StaticResource cvs}}" />
<ComboBoxItem>
<Button Click="Button_Click" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" Content="{x:Static prop:Resources.INSERT_BTN}"/>
</ComboBoxItem>
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
這是Button_Click
事件:
private void Button_Click(object sender, RoutedEventArgs e)
{
Button s = sender as Button;
var popup = new System.Windows.Controls.Primitives.Popup();
popup.AllowsTransparency = true;
popup.Child = new myCustomView();
popup.PlacementTarget = s;
popup.Placement = System.Windows.Controls.Primitives.PlacementMode.Top;
popup.IsOpen = true;
popup.StaysOpen = true;
}
問題是,當我單擊myCustomView
定義的任何控件時, Popup
myCustomView
將失去焦點並關閉。 我該如何強迫它保持打開狀態?
編輯1:
由於myCustomView
有自己的ViewModel
我試圖通過將其IsOpen
屬性綁定到視圖模型內部的布爾值來破解Popup
以使其保持打開狀態,如下所示:
popup.DataContext = myCustomViewModel;
Binding b = new Binding();
b.Source = myCustomViewModel;
b.Path = new PropertyPath("stayOpened");
b.Mode = BindingMode.TwoWay;
b.UpdateSourceTrigger = UpdateSourceTrigger.Default;
BindingOperations.SetBinding(popup, Popup.IsOpenProperty, b);
// BindingOperations.SetBinding(popup, Popup.StaysOpenProperty, b); tried both IsOpened and StaysOpen
但是焦點切換仍然會殺死我的Popup
。
您可以將PlacementTarget
設置為父ItemsControl
,然后設置Popup
的VerticalOffset
和HorizontalOffset
屬性以指定其在屏幕上的確切位置,例如:
private void btn_Click(object sender, RoutedEventArgs e)
{
Button s = sender as Button;
System.Windows.Controls.Primitives.Popup popup = new System.Windows.Controls.Primitives.Popup();
popup.AllowsTransparency = true;
popup.Child = new myCustomView();
//some stuff needed to recognise which button was pressed
popup.PlacementTarget = ic; //<-- "ic" is the name of the parent ItemsControl
Point p = s.TranslatePoint(new Point(0, 0), ic);
popup.VerticalOffset = p.Y; //adjust this value to fit your requirements
popup.HorizontalOffset = p.X; //adjust this value to fit your requirements
popup.IsOpen = true;
popup.StaysOpen = true;
}
您可以像這樣將Popup.StaysOpen設置為true
<Popup StaysOpen="True"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.