WPF 如何找到被单击的列表框项目

发布于 2024-10-13 06:33:21 字数 314 浏览 3 评论 0原文

我有一个 WPF 应用程序,其中有一个列表框,其中填充了“匹配”类型的项目。 如何使按钮(包含在项目中)实际选择该项目以便我可以提取该值?

这是我的代码:两者都不起作用,因为单击按钮实际上并未选择该项目

private void LayButton_Click(object sender, RoutedEventArgs e)
{
    var x = (Market)ListBoxSelectedMarket.SelectedItem;
    var y = (sender as ListBoxItem);

}

谢谢

I have a WPF application in which there's a listbox filled with items of type 'Match'.
How do I make the button(contained within the item) actually select the item so that I might extract the value?

Here is my code: neither works since clicking the button doesn't actually select the item

private void LayButton_Click(object sender, RoutedEventArgs e)
{
    var x = (Market)ListBoxSelectedMarket.SelectedItem;
    var y = (sender as ListBoxItem);

}

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一身软味 2024-10-20 06:33:21

您应该能够从单击的按钮使用 DataContext 并从那里获取 ListBoxItem 容器,然后选择它。

private void LayButton_Click(object sender, RoutedEventArgs e)
{  
    Button button = sender as Button;
    var dataContext = button.DataContext;
    ListBoxItem clickedListBoxItem = ListBoxSelectedMarket.ItemContainerGenerator.ContainerFromItem(dataContext) as ListBoxItem;
    clickedListBoxItem.IsSelected = true;
}

You should be able to use the DataContext from the clicked Button and get the ListBoxItem container from there, and then select it.

private void LayButton_Click(object sender, RoutedEventArgs e)
{  
    Button button = sender as Button;
    var dataContext = button.DataContext;
    ListBoxItem clickedListBoxItem = ListBoxSelectedMarket.ItemContainerGenerator.ContainerFromItem(dataContext) as ListBoxItem;
    clickedListBoxItem.IsSelected = true;
}
独自唱情﹋歌 2024-10-20 06:33:21

如果您要绑定到一个对象,则可以使用替代方法(在 VB 中),

这将为您提供一个要使用的对象实例,并保存列表框中的任何映射字段

Private Sub OTC_Settled_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim pr_YourObject As New YourObject
        Dim btn As Button = CType(sender, Button)
        OTC = DirectCast(btn.DataContext, pr_YourObject)
     End Sub

If you are binding to an object an alternative method could be (in VB)

This then gives you an instance of your object to play with and saves you having any mapping fields on the listbox

Private Sub OTC_Settled_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim pr_YourObject As New YourObject
        Dim btn As Button = CType(sender, Button)
        OTC = DirectCast(btn.DataContext, pr_YourObject)
     End Sub
我偏爱纯白色 2024-10-20 06:33:21

我没有做过太多 WPF 编程,但如果它与 WinForms 容器对象的工作方式相同,您可以尝试获取按钮的父级。

I haven't done much WPF programming, but you could try getting the parent of the button if it works the same as a WinForms container object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文