获取列表框SelectedItems [英] Get ListBox SelectedItems

查看:89
本文介绍了获取列表框SelectedItems的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得这应该是一个简单的功能,但是我不知道如何在不使用背后代码的情况下将其绑定到列表框中的选定项目.

I feel like this should be a simple feature but I don't know how to bind to the selected items in a Listbox without using code behind.

我有一个带有Datatemplate的列表框,其中包含一个复选框.我想获取已选中/已选中项目的列表.我该怎么做?

I have a Listbox with Datatemplate containing a Checkbox. I want to get the list of the checked/selected items. How do I do this?

如果我无法获取SelectedItems,我想绑定到每次选择某项时都会触发"SelectedProduct"的东西,这样我就可以遍历"ProductList"并找到选中的项目.但是,SelectedItem不会在我每次单击某个项目时触发.

If I cannot get the SelectedItems, I want to bind to something that triggers "SelectedProduct" every time something gets selected so I can iterate through the "ProductList" and find the checked items. However, SelectedItem does not trigger every time I click on an item.

这是我的代码:

<ListBox ItemsSource="{Binding ProductList}" SelectedItem="{Binding SelectedProduct}" SelectionMode="Multiple">
<ListBox.ItemTemplate>
    <DataTemplate>
        <CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}" Content="{Binding ID}" Margin="2"/>
    </DataTemplate>
</ListBox.ItemTemplate>

<ListBox.ItemContainerStyle>
    <Style TargetType="{x:Type ListBoxItem}">
        <Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsChecked}"/>
    </Style>
</ListBox.ItemContainerStyle>

推荐答案

一个普通的理性人会认为 SelectedItems 应该是可绑定的.除了...不是.那糟透了.

A normal rational person would think SelectedItems should be bindable. Except... it isn't. And that sucks.

您已经习惯了通常的方法,将 IsSelected 绑定到数据对象中的属性,然后执行以下操作:

You have already hit on the usual approach, bind IsSelected to a property in your data object, then do something like:

myCollection.Where(i => i.Selected);

根据 MSDN SelectedItem 可以返回 any 所选项目,因此,其触发时序语义最多将是不确定的.在选择内容的任何部分更改时获取通知会很棘手,但是当 Selected 属性更改时,您始终可以运行逻辑(例如,引发事件VM侦听).

According to MSDN SelectedItem can return any selected item if the mode is set to "Multiple", so its trigger timing semantics are going to be undefined at best. Getting a notification when any part of the selection changes is going to be tricky, but you can always run logic when the Selected property gets changed (for example, raise an event the VM listens for).

这篇关于获取列表框SelectedItems的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆