如何在RadioButton检查时打开WPF Popup?

时间:2015-06-18 04:57:05

标签: wpf popup

我有RadioButtonPopup。我希望在选中Popup时打开RadioButton并在Popup时关闭LostFocus,而不取消选中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;
}   

检查时是打开弹出窗口,但是当丢失未经检查的单选按钮时。

我为Mode=OneWay设置了IsOpen,它是打开的弹出窗口,并且没有取消选中radionButton,但是它已经工作了一段时间。

2 个答案:

答案 0 :(得分:1)

以下是仅在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,您可以通过单击其外的任何位置来关闭Popup。

更新1:

在StackPanel.Resources中添加它并命名您的Popup。

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

这将被添加到codebehind:

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

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

答案 1 :(得分:0)

请改为尝试:

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