XAML 单击叠加按钮时忽略ListViewItem的EventViewer

gc0ot86w  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(71)

我有一个程序,我用一系列我以编程方式添加的ListView项目创建一个ListView。我还覆盖了一个按钮,允许您从ListView中删除该项目。然而,当我单击它时,它激活了我为整个ListView添加的EventSetter,当单击此按钮时,我希望忽略它。
有没有一种方法可以让它在你点击那个按钮的时候,只触发那个事件,而不是ListViewItem的事件?我试过在按钮点击的函数中设置e.Handled=true,但是没有用。
先谢了。

<ListView
    x:Name="SavedClipboardList"  
    HorizontalAlignment="Center"
    VerticalAlignment="Center"
    ScrollViewer.VerticalScrollBarVisibility="Hidden"
    ScrollViewer.HorizontalScrollBarVisibility="Disabled"
    Width="600"
    Height="460"
    Background="#282828"
    BorderThickness="0"
    HorizontalContentAlignment="Stretch"
    VirtualizingPanel.ScrollUnit="Pixel">

    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="BorderBrush" Value="LightGray" />
            <Setter Property="BorderThickness" Value="1,1,1,1" />
            <Setter Property="Margin" Value="20, 0, 20, 5" />
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
            <EventSetter Event="PreviewMouseLeftButtonDown" Handler="SavedClipboardList_ItemClick"/>
        </Style>
    </ListView.ItemContainerStyle>

    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <StackPanel Orientation="Horizontal" Width="525">
                    <Image Source= "/Assets/Placeholder.png" HorizontalAlignment="Left"/>
                    <TextBlock Text= "{Binding body}" FontWeight="Bold" Foreground="#ffffff"/>
                </StackPanel>
                
                <StackPanel Orientation="Vertical" HorizontalAlignment="Right" Width="Auto">
                    <Button BorderThickness="0" Background="Transparent" Foreground="#FFFFFF" Click="btnRemove_Click">X</Button>
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>

</ListView>

字符串

z4bn682m

z4bn682m1#

PreviewMouseLeftButtonDown是一个隧道事件,在ButtonClick事件之前引发。
有没有一种方法可以让它在你点击那个按钮的时候,只触发那个事件,而不触发ListViewItem的事件?
如果你不想在点击Button时处理隧道事件,你可以检查传递给SavedClipboardList_ItemClick事件处理程序的MouseButtonEventArgsOriginalSource是否是Button的一部分:

private void SavedClipboardList_ItemClick(object sender, MouseButtonEventArgs e)
{
    if (e.OriginalSource is Button || (e.OriginalSource is DependencyObject dependencyObject
        && FindParent<Button>(dependencyObject) != null))
        return;

    // handle item click just like before...
}

private static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
    var parent = VisualTreeHelper.GetParent(dependencyObject);
    if (parent == null)
        return null;

    var parentT = parent as T;
    return parentT ?? FindParent<T>(parent);
}

private void btnRemove_Click(object sender, RoutedEventArgs e)
{
   // handle button click...
}

字符串
但是,您无法阻止引发PreviewMouseLeftButtonDown事件。

相关问题