如何在选中 RadioButton 时打开 WPF 弹出窗口?

How to open a WPF Popup when RadioButton checked?

我有一个 RadioButton 和一个 Popup。我想在选中 RadioButton 时打开 Popup 并在 LostFocus 时关闭 Popup,而不是未选中 RadioButton.

我用这个代码。

<StackPanel>
 <RadioButton x:Name="RadioButtonSave" IsChecked="{Binding IsSave}">Save</RadioButton>
 <RadioButton x:Name="RadioButtonNotSave" LostFocus="RadioButtonNotSave_OnLostFocus" IsChecked="{Binding IsSave,Converter={StaticResource ToNegativeConverter}}">Not Save</RadioButton>
</StackPanel>
<Popup x:Name="Popup" IsOpen="{Binding IsChecked,ElementName=RadioButtonNotSave}" StaysOpen="True" Placement="Left" PlacementTarget="{Binding ElementName=RadioButtonNotSave}"></Popup>

private void RadioButtonNotSave_OnLostFocus(object sender, RoutedEventArgs e)
{
 Popup.IsOpen = false;
}   

它在选中时打开弹出窗口,但当 lostfocuse 未选中单选按钮时。

我为 IsOpen 设置了 Mode=OneWay ,它是打开的弹出窗口,并且在失去焦点时不要取消选中 radionButton,但它工作了一次。

这是一种仅在 XAML:

中实现的方法
<Window x:Class="RadioButtonAndPopup.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel>
        <StackPanel.Resources>
            <Style TargetType="{x:Type RadioButton}">
                <EventSetter Event="Click" Handler="EventSetter_OnHandler"/>
            </Style>
      </StackPanel.Resource>
        <RadioButton x:Name="RadioBtn" Content="TestPopup"/>
        <Popup x:Name="myPopup" IsOpen="{Binding IsChecked, ElementName=RadioBtn, Mode=OneWay}" Placement="Mouse" StaysOpen="False">
            <Border Background="LightBlue">
                <TextBlock>Popup</TextBlock>
            </Border>
        </Popup>
    </StackPanel>
</Grid>

将 StaysOpen 设置为 false,您将能够通过单击弹出窗口外的任意位置来关闭该弹出窗口。

更新 1:

将此添加到 StackPanel.Resources 并命名您的 Popup。

<Style TargetType="{x:Type RadioButton}">
      <EventSetter Event="Click" Handler="EventSetter_OnHandler"/>
</Style>

这将被添加到代码隐藏中:

private void EventSetter_OnHandler(object sender, RoutedEventArgs e)
{
     myPopup.IsOpen = true;
}

现在 Popup 将在该 Click 事件上打开,而不是在 IsChecked 绑定上打开。

试试这个:

private void RadioButtonNotSave_OnLostFocus(object sender, RoutedEventArgs e)
{
   IsChecked = false;
}