c# - ListView.ItemClick 未在具有自定义 ItemContainerStyle 的 ListView 中触发

标签 c# windows-runtime winrt-xaml

在具有自定义 ItemContainerStyleListView 中,即使 IsItemClickEnabled 设置为 True,也不会触发 ItemClick 。我的 XAML 代码位于自定义控件模板内的 ResoureDictionary 中,并且是

<ListView ItemsSource="{TemplateBinding History}"
          ItemTemplate="{StaticResource HistoryItemTemplate}"
          ItemContainerStyle="{StaticResource HistoryItemContainerStyle}"
          IsHitTestVisible="True" SelectionMode="None" IsSwipeEnabled="False"
          CanDragItems="False" CanReorderItems="False"
          IsItemClickEnabled="True" Width="400" Margin="50,0,0,0" >
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel Margin="0" />
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
</ListView>

HistoryItemTemplate

<Style x:Key="HistoryItemContainerStyle" TargetType="ListViewItem">
    <Setter Property="BorderThickness" Value="0,0,0,1" />        
    <Setter Property="Margin" Value="0" />
    <Setter Property="Padding" Value="0" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListViewItem">
                <Button Style="{StaticResource HistoryItemButtonStyle}"
                        Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" />                    
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

C#代码是

protected override void OnApplyTemplate()
{
    base.OnApplyTemplate();

    var historyListView = GetTemplateChild("HistoryListView") as ListView;
    if (historyListView != null)
        historyListView.ItemClick += OnHistoryItemClicked;
}

我还尝试将 ListViewItem 模板的 IsHitTestVisible 属性中的按钮设置为 False。这是行不通的。如果删除自定义 ItemContainersStyle,一切都会正常工作。

最佳答案

发生这种情况是因为模板中的 Button 元素阻止 ListViewItem 处理指针事件。您需要将 Button 替换为另一个元素,例如 Border

关于c# - ListView.ItemClick 未在具有自定义 ItemContainerStyle 的 ListView 中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27592065/

相关文章:

windows-8 - 如何在 WinRT XAML 中拥有 DesignTime 数据?

c# - 为什么调用 await 会过早地完成父任务?

c# - 使用 C# 在 ComboBox 中放置驱动器列表的最有效方法是什么?

c# - 在 c# (winForms) 中用字符串列表制作树结构

c# - Windows.winmd 处于 azure 辅助角色

c# - Windows Phone 8.1 数据绑定(bind) ListView [XAML]

c# - 您如何在 ASP.Net MVC 中找到哪个 View 称为哪个局部 View

c# - 为什么要使用接口(interface)和抽象而不是抽象?

c# - Windows Phone 8.1 中的警报代码

xaml - ObservationCollection 使用 MVVM 架构在 PCL 内部的 ViewModel 中实现 ISupportIncrementalLoading,以支持 WinRT 和 WP8/WinPRT