开发者

keyup event in wpf listbox datatemplate

开发者 https://www.devze.com 2023-04-10 10:29 出处:网络
<ListView SelectionChanged=\"RecordSelected\" Height=\"134\" HorizontalAlignment=\"Left\" Margin=\"10,10,0,0\" Name=\"processList\" VerticalAlignment=\"Top\" Width=\"207\">
            <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}">
                                <Ch开发者_Python百科eckBox 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.


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


Use the PreviewKeyUp event. That always fires.

You may also want to try PreviewKeyDown.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消