簡體   English   中英

如何防止彈出窗口失去焦點?

[英]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 ,然后設置PopupVerticalOffsetHorizontalOffset屬性以指定其在屏幕上的確切位置,例如:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM