选择ListboxItem时,Wpf关闭弹出窗口

时间:2013-04-25 13:01:30

标签: wpf listbox popup

我在弹出窗口中有列表框。从列表框中选择项目后,如何关闭弹出窗口; 这是代码:

 <Popup x:Name="ColorPopup" AllowsTransparency="True" 
 IsOpen="{Binding ElementName=ColorToggle, Path=IsChecked}" Placement="Bottom" StaysOpen="False" PlacementTarget="{Binding ElementName=ColorToggle}">

  <Border x:Name="DropDownBorder1" BorderBrush="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}" Margin="0, 0,5,5" BorderThickness="1" Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}" Effect="{DynamicResource WindowShadowEffect}">
      <ListBox Name="ColorList" VerticalContentAlignment="Stretch" Margin="1, 3, 1, 3"   IsEnabled="True" Grid.Column="0" Background="Transparent" HorizontalContentAlignment="Center" SelectedItem="{Binding fColor}" SelectionMode="Single" Style="{StaticResource HorizontalListBoxStyle2}" ItemsSource="{Binding FillColors}">
      </ListBox>

   </Border>

</Popup>

1 个答案:

答案 0 :(得分:2)

订阅SelectionChanged活动。

您可以在代码隐藏中执行此操作:

private void ListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
    // ColorPopup.IsOpen = false; ?? or ColorToggle.IsChecked = false; 
}
<ListBox SelectionChanged="ListBox_SelectionChanged_1" ... />

或者如果您使用MVVM模式......

对于MVVM-Light来说可能是这样的:

<ListBox ...>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <cmd:EventToCommand Command="{Binding Path=ClosePopupCommand}" PassEventArgsToCommand="True" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ListBox>

或者棱镜可能几乎相同:

 <ListBox>
      <i:Interaction.Triggers>
           <i:EventTrigger EventName="SelectionChanged">
                <prism:InvokeCommandAction Command="{Binding Path=ClosePupupCommand}" />
           </i:EventTrigger>
      </i:Interaction.Triggers>
 </ListBox> 

或者如果你有肮脏的头脑,你也可以在fColor属性设置器中关闭弹出窗口。 :)

    public object fColor
    {
        get
        {
            return this.fColorField;
        }

        set
        {
            this.fColorField= value;
            IsColorToggelChecked = false;
            RaisePropertyChanged(() => this.fColor);
        }
    }