编程语言
首页 > 编程语言> > c# – WPF ListViewItem事件未在触摸屏上正常触发

c# – WPF ListViewItem事件未在触摸屏上正常触发

作者:互联网

 <Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        WindowState="Maximized"
        Title="MainWindow" Height="550" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="4*"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBox Name="TextBox" VerticalContentAlignment="Center" FontSize="30" ></TextBox>
        <ListView Grid.ColumnSpan="6"  Grid.Row="1"
                     x:Name="GridControlProducts"
                    SelectionMode="Single"
                    ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                    ScrollViewer.VerticalScrollBarVisibility="Disabled">
            <ListView.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ListView.ItemsPanel>
            <ListView.ItemContainerStyle>
                <Style TargetType="{x:Type ListViewItem}">
                    <Setter Property="Width" Value="200"/>
                    <Setter Property="Height" Value="200"/>
                    <EventSetter Event="PreviewMouseDown" Handler="button_Click" />
                </Style>
            </ListView.ItemContainerStyle>
        </ListView>       


        <Button Content="Close" Grid.Column="0" Grid.Row="2" Click="Button_Click_1" ></Button>

    </Grid>
</Window>
// code behind
public MainWindow()
        {
            InitializeComponent();

            for (int i = 0; i < 10; i++)
            {
                this.GridControlProducts.Items.Add("Test");
            }
        }

 private int c = 1;
        private void button_Click(object sender, RoutedEventArgs e)
        {
            this.TextBox.Text = this.c++.ToString();
        }

我有一个WPF触摸屏应用程序,其中包含列表视图模板中的产品列表.

使用鼠标一切都按预期工作.但是,在触摸屏上,触摸事件不会每次都触发.例如,如果我连续按下列表视图中的10个按钮,则可能会注册7个触摸,而3个触摸则不会.

如果我触摸它自己的标准按钮,它会非常敏感.我的模板中的按钮不是(非常命中和错过).

我创建了一个简单的测试应用程序(见上文)来测试它,我的测试应用程序上的行为是相同的.

当它没有注册时,仍然选择了先前选择的listviewitem,并且我选择的未注册的项目是浅蓝色(就像当你用鼠标悬停时)

任何帮助将不胜感激.

解决方法:

摘要

>切勿在ListView / ListBox中使用Click事件,而是使用PreviewMouseDown.
>您的触摸设备的触摸精度可能低于其他大多数设备.

细节

几年前我遇到了同样的问题,发现它在不同的触摸设备上的行为有所不同.在大多数触控设备上,触控每次都有效.但在其他一些情况下,触摸可能会随机丢失.

如果您尝试注意触摸屏上的移动,您可能会发现如果手指在按下时移动了一小段距离,触摸将会丢失.此行为仅发生在ListViewItem或ListBoxItem上,因为ListView和ListBox处理触摸事件并为其触摸滚动行为重新加载它们.

同一控件上的MouseDown和MouseUp构成Click事件,触摸事件也是如此.但是在ListBox或ListView上,单击事件必须位于同一点而不是相同的控件.因为ListView / ListBox不需要首先处理鼠标事件,所以鼠标单击工作正常.

不同类型的触摸设备之间的区别在于它们的触摸精度.精度越低,触摸事件就越多.

你能做的是:

>切勿在ListView / ListBox中使用Click事件,而是使用PreviewMouseDown.

标签:c,events,wpf,xaml,touchscreen
来源: https://codeday.me/bug/20190701/1346978.html