【问题标题】:PreviewKeyDown of checkbox in Multi Select ComboBox in WPFWPF中Multi Select ComboBox中复选框的PreviewKeyDown
【发布时间】:2015-11-01 13:38:54
【问题描述】:

我使用this文章创建多选ComboBox

我想在按下空格键时选择/取消选择每个项目内的CheckBox

我尝试为CheckBox 添加PreviewKeyDown,但没有引发该事件。

我也尝试在StackPanel 中添加PreviewKeyDown,但我无法获得当前选中的CheckBox 的选定项目。

【问题讨论】:

  • 将 PreviewKeyDown 事件添加到主窗口而不是 CheckBox 。
  • 如何获取选中的复选框?
  • if (sender is ComboBox && ((ComboBox )sender ).IsDropDownOpen && (((ComboBox )sender ).Items[0] as CheckBox).IsChecked = true){....}

标签: c# wpf checkbox combobox


【解决方案1】:

您需要处理组合框的 KeyUp 并确保下拉菜单已打开。

更新:

<Grid>
    <ComboBox x:Name="cbo" KeyUp="ComboBox_KeyUp" Height="30" Width="200">
        <CheckBox Content="checkbox1"/>
        <CheckBox Content="checkbox2"/>
        <CheckBox Content="checkbox3"/>
        <CheckBox Content="checkbox4"/>
        <CheckBox Content="checkbox5"/>
    </ComboBox>
</Grid>
///////////////////////////
private void ComboBox_KeyUp(object sender, KeyEventArgs e)
    {
        if (cbo.IsDropDownOpen)
        {
          // select first and second
         (cbo.Items[0] as CheckBox).IsChecked = true;
         (cbo.Items[1] as CheckBox).IsChecked = true;

        }
    }

【讨论】:

  • 组合框打开,我想选中印刷空间中选定项目中的复选框。
  • @ar.gorgin 我添加了一些代码给你一个想法。
  • 我使用多选组合框,我想为项目添加事件。
【解决方案2】:

我使用EventSetter

<ComboBox.Resources>
  <Style TargetType="{x:Type ComboBoxItem}">
   <EventSetter Event="PreviewKeyDown" Handler="EventSetter_OnHandler" />
  </Style>
</ComboBox.Resources>

在后面的代码中。

private void EventSetter_OnHandler(object sender,KeyEventArgs e)
 {
 var item=((ComboBoxItem)sender).DataContext as Node;
 item.IsSelected=!item.IsSelected;
 }

【讨论】:

    猜你喜欢
    • 2016-12-18
    • 1970-01-01
    • 2010-10-25
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    相关资源
    最近更新 更多