简体   繁体   中英

Wpf combobox selected item by mouse

I have a combobox of text align buttons and when I try to choose one of them by mouse click, selected item doesn't change. It seems like ComboBoxItem doen't get Click event. Does any one know how to handle that?

<ComboBox x:Name="FontAligmentCombo">
  <ComboBoxItem IsSelected="True">
    <Button Command="EditingCommands.AlignLeft"
            ToolTip="Align Left">
        <Viewbox>
            <ContentPresenter Content="{DynamicResource icon8_Win10_AlignLeft}" />
        </Viewbox>
    </Button>
  </ComboBoxItem>
  <ComboBoxItem>
    <Button Command="EditingCommands.AlignCenter"
            ToolTip="Align Center">
        <Viewbox>
            <ContentPresenter Content="{DynamicResource icon8_Win10_AlignCenter}" />
        </Viewbox>
    </Button>
  </ComboBoxItem>
</ComboBox>
<ComboBoxItem IsSelected="True">
<Button Command="EditingCommands.AlignLeft"
        ToolTip="Align Left">
    <Viewbox>
        <ContentPresenter Content="{DynamicResource icon8_Win10_AlignLeft}" />
    </Viewbox>
</Button>

You hardcoded IsSelected to True. Try handling selected Items in Combobox itself by SelectedItem or SelectedIndex property. In your case Index makes sense. If you cannot, you should bind the bool value.

The Button "swallows" the click. You will have to select the corresponding ComboBoxItem programmatically.

Try this:

<ComboBox x:Name="FontAligmentCombo">
    <ComboBox.Resources>
        <Style TargetType="Button">
            <EventSetter Event="Click" Handler="OnClick" />
        </Style>
    </ComboBox.Resources>
    <ComboBoxItem IsSelected="True">
        <Button Command="EditingCommands.AlignLeft" ToolTip="Align Left">
            <Viewbox>
                <ContentPresenter Content="{DynamicResource icon8_Win10_AlignLeft}" />
            </Viewbox>
        </Button>
    </ComboBoxItem>
    <ComboBoxItem>
        <Button Command="EditingCommands.AlignCenter" ToolTip="Align Center">
            <Viewbox>
                <ContentPresenter Content="{DynamicResource icon8_Win10_AlignCenter}" />
            </Viewbox>
        </Button>
    </ComboBoxItem>
</ComboBox>

private void OnClick(object sender, RoutedEventArgs e)
{
    Button button = sender as Button;
    ComboBoxItem cbi = FindParent<ComboBoxItem>(button);
    if (cbi != null)
    {
        FontAligmentCombo.SelectedItem = cbi;
        FontAligmentCombo.IsDropDownOpen = false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM