C# WPF ListBox 按钮选择的项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1139996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:11:09  来源:igfitidea点击:

WPF ListBox Button Selected Item

c#.netwpflistbox

提问by Nate

I have a listbox with some textblocks and a button -- in the button's codebehind it calls a method passing the currently selected listbox item, this works great. The issue is that when I select an item and then click the button on another item it doesn't update the "SelectedItem" property -- is there a way Xaml or C# that I can force a button click to select the parent ListBoxItem?

我有一个带有一些文本块和一个按钮的列表框——在按钮的代码隐藏中,它调用一个传递当前选择的列表框项目的方法,这很好用。问题是,当我选择一个项目然后单击另一个项目上的按钮时,它不会更新“SelectedItem”属性——有没有办法让 Xaml 或 C# 强制单击按钮来选择父 ListBoxItem?

Xaml

xml

<DataTemplate>
    <Grid>
        <Button x:Name="myButton" Click="myButton_Click" Height="30" Width="30">
            <Image Source="Resources\Image.png" />
        </Button>
        <TextBlock Text="{Binding DataField}"></TextBlock>
    </Grid>
</DataTemplate>

采纳答案by rooks

var curItem = ((ListBoxItem)myListBox.ContainerFromElement((Button)sender)).Content;

回答by Kenan E. K.

When a Button is clicked, it sets e.Handled to true, causing the routed event traversal to halt.

单击 Button 时,它会将 e.Handled 设置为 true,从而导致路由事件遍历停止。

You could add a handler to the Button which raises the routed event again, or finds the visual ancestor of type ListBoxItem and sets its IsSelected property to true.

您可以向 Button 添加一个处理程序,它会再次引发路由事件,或者找到 ListBoxItem 类型的视觉祖先并将其 IsSelected 属性设置为 true。

EDIT

编辑

An extension method like this:

这样的扩展方法:

public static DependencyObject FindVisualAncestor(this DependencyObject wpfObject, Predicate<DependencyObject> condition)
{
    while (wpfObject != null)
    {
        if (condition(wpfObject))
        {
            return wpfObject;
        }

        wpfObject = VisualTreeHelper.GetParent(wpfObject);
    }

    return null;
}

Usage:

用法:

myButton.FindVisualAncestor((o) => o.GetType() == typeof(ListBoxItem))