coder
coder

Reputation: 4313

keyup event in wpf listbox datatemplate

            <ListView SelectionChanged="RecordSelected" Height="134" HorizontalAlignment="Left" Margin="10,10,0,0" Name="processList" VerticalAlignment="Top" Width="207">
                <ListView.ItemTemplate>
                    <DataTemplate x:Name="record" DataType="{x:Type local:MyApp}">
                        <StackPanel Name="cell" Orientation="Vertical" KeyUp="cell_KeyUp">
                            <StackPanel KeyUp="cell_KeyUp" GotFocus="RecordSelected" KeyDown="RecordSelected" MouseDown="RecordSelected" Orientation="Horizontal" Tag="{Binding MyApp}">
                                <CheckBox BorderThickness="1" IsChecked="{Binding IsChecked}" Margin="3,3,3,3" Name="checkbox" />
                                <TextBlock GotFocus="RecordSelected" HorizontalAlignment="Left" KeyDown="RecordSelected" Margin="3,0,0,3" Name="displayname" Text="{Binding DisplayName}" VerticalAlignment="Center" Width="200" />
                            </StackPanel>
                        </StackPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

I added a KeyUp event on both the stackpanels inside the datatemplate, but it wouldn't fire.

Upvotes: 2

Views: 2476

Answers (3)

C.M.
C.M.

Reputation: 1561

My awful solution: I used a mouse event since I couldn't get any key events to work.

Upvotes: 0

Fredrik Hedblad
Fredrik Hedblad

Reputation: 84666

The KeyUp event won't trigger since it is the ListViewItem that has the focus. Subscribe to the KeyUp event in the ItemContainerStyle instead

<ListView ...>
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <EventSetter Event="KeyUp" Handler="cell_KeyUp"/>
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.ItemTemplate>
        <!-- ... -->
    </ListView.ItemTemplate>
</ListView>

In the event handler the sender will be the focused ListViewItem. Cast Content of it to your source and toggle IsChecked. This will work if your source class implements INotifyPropertyChanged. Otherwise, you can search the Visual Tree to find the child CheckBox of the ListViewItem

Upvotes: 4

Yatrix
Yatrix

Reputation: 13795

Use the PreviewKeyUp event. That always fires.

You may also want to try PreviewKeyDown.

Upvotes: 0

Related Questions