Combobox ItemTemplate dont accept click

559 views Asked by At

I made a Usercontrol with a Combobox with itemTemplate. I set a an event trigger for click on Item. but its not work completely. it dosent accept the click. around the template or empty place before my text. this is my code

        <Combobox>
        <Combobox.ItemTemplate>
            <DataTemplate>
                <Grid Height="25" FlowDirection="RightToLeft">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="25" />
                        <ColumnDefinition MinWidth="100" />
                        <ColumnDefinition Width="25" />
                    </Grid.ColumnDefinitions>
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="MouseLeftButtonUp">
                            <command:EventToCommand Command="{Binding Command}"
                                                    CommandParameter="{Binding CommandParameter}" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                    <Image Height="20" Width="25" Grid.Column="0" VerticalAlignment="Center"
                                HorizontalAlignment="Center" />
                    <TextBlock Text="{Binding Title}" Grid.Column="1" VerticalAlignment="Center" />
                    <TextBlock Grid.Column="2" />
                </Grid>
            </DataTemplate>
        </Combobox.ItemTemplate>
    </Combobox>

it is a usercontrol that binds to a list of object contains Command and commandparameter, on click on each item one command should be raised.

2

There are 2 answers

3
user12345679 On

What's wrong with SelectionChanged event of ListBox? You could bind to that.

DataTemplate is for the data not for UI events. You use data-templates to tell WPF how you want to display data. At most you could have DataTriggers (which is again belong to data).

If you want to trap the click event on items, use ItemContainerStyle. The ItemContainerStyle is for styling the container of dataitem, which is ListBoxItem in this case.

Something of this sort might help:

<Style TargetType="ListBoxItem">
<Style.Triggers>
   <EventTrigger RoutedEvent="Mouse.MouseEnter">
  </EventTrigger>
 </Style.Triggers>
</Style>
4
eran otzap On

Visual elements need to be assigned a brush in order for hit testing to take place. (I did say IsHitTestVisibile so you wouldn't confuse the two).

You can do the following above your ItemTemplate in the Container that hosts it like so :

<ComboBox>
    <ComboBox.ItemContainerStyle>
         <Style TargetType="ComboBoxItem" BasedOn="{StaticResource {x:Type ComboBoxItem}}"> <!-- Or based on any other ComboboxItem style you have-->
             <Setter Property="Background" Value="Transparent" />
         </Style>
     </ComboBox.ItemContainerStyle>
</ComboBox>

FYI : IsHitTestVisibile is a flag stating that even if a Hit test did pass you can choose to disregard it.