我想要一個可以打開和關閉包含可點擊控制元件的區域的按鈕。目前我嘗試通過彈出視窗來實作這一點。XAML:
<Window x:Class="PopupTrouble.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid Height="200" Width="200" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Content="Open popup" Click="Button_Click"/>
<Popup x:Name="PopupInstance"
AllowsTransparency="True"
StaysOpen="False">
<Border BorderThickness="1" BorderBrush="Black">
<StackPanel>
<TextBlock Text="Some other clickable controls"/>
<RadioButton IsChecked="True" Content="Option one" GroupName="Group"></RadioButton>
<RadioButton IsChecked="False" Content="Option two" GroupName="Group"></RadioButton>
</StackPanel>
</Border>
</Popup>
</Grid>
</Window>
檔案后面的代碼:
using System.Windows;
namespace PopupTrouble
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e) => PopupInstance.IsOpen = !PopupInstance.IsOpen;
}
}
問題是當彈出視窗打開時,按鈕會重新打開它而不是關閉它。如果我是對的,這是因為當我單擊按鈕時彈出視窗失去焦點。我不能只將 StaysOpen 屬性設定為 true,因為這樣在滑鼠滾動或滑鼠單擊其他控制元件期間彈出視窗將保持不變。
當前行為的 Gif (gifyu.com)
有什么方法可以改變這種行為并使 WPF 在我單擊按鈕時不改變焦點?
我嘗試使用 FocusManager 來實作這一點,并檢查獲得焦點的新元素是否是按鈕,但遇到另一個問題 - 彈出視窗中的控制元件無法正常作業。
uj5u.com熱心網友回復:
也許這個解決方案將適合您而不使用 Code Behind。
<Grid Height="200" Width="200" HorizontalAlignment="Center" VerticalAlignment="Center">
<ToggleButton x:Name="toggleButton"
IsChecked="False">
<ToggleButton.Style>
<Style TargetType="ToggleButton">
<Setter Property="Content" Value="Open popup"/>
<Style.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Content" Value="Close popup"/>
</Trigger>
</Style.Triggers>
</Style>
</ToggleButton.Style>
</ToggleButton>
<Popup x:Name="PopupInstance"
AllowsTransparency="True"
IsOpen="{Binding IsChecked, ElementName=toggleButton, Mode=TwoWay}">
<Border BorderThickness="1" BorderBrush="Black">
<StackPanel>
<TextBlock Text="Some other clickable controls"/>
<RadioButton IsChecked="True" Content="Option one" GroupName="Group"></RadioButton>
<RadioButton IsChecked="False" Content="Option two" GroupName="Group"></RadioButton>
</StackPanel>
</Border>
</Popup>
</Grid>
當我滾動滑鼠或單擊彈出視窗或按鈕外部時,彈出視窗不會關閉。
當按鈕失去焦點時,可以關閉彈出視窗:
<Popup x:Name="PopupInstance"
AllowsTransparency="True"
IsOpen="{Binding IsChecked, ElementName=toggleButton, Mode=TwoWay}"
StaysOpen="{Binding IsFocused, ElementName=toggleButton}">
或者這個變種:
<Popup x:Name="PopupInstance"
AllowsTransparency="True"
IsOpen="{Binding IsChecked, ElementName=toggleButton, Mode=TwoWay}"
StaysOpen="{Binding IsMouseOver, ElementName=toggleButton}">
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/527037.html
上一篇:如果元素有孩子,我該如何洗掉它?
