繁体   English   中英

获取Listbox.SelectedItems

[英]Getting Listbox.SelectedItems

因此,如果我有一个已被分配数据并绑定到列表框项目模板的变量集合,那么如何根据列表框项目的选择来获取数据集合?

<ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical" Height="500">
                    <Image Source="{Binding img }" Width="853" Height="480" VerticalAlignment="Top" Margin="0,10,8,0"/>
                    <StackPanel Width="370">
                        <TextBlock Text="{Binding text}" Foreground="#FFC8AB14" FontSize="28" />
                        <TextBlock Text="{Binding text2}" TextWrapping="Wrap" FontSize="24" />
                    </StackPanel>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>

C#:

 public class collection
    {
        public string text { get; set; }
        public string img { get; set; }
        public string text2 { get; set; }
    }

    private void ListBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
       ListBox1.SelectedItems
        //how do you get the selected data in the img, text, text2 on selection?
    }

因为您将集合类绑定到ListBox中,所以我认为这是在背面的viewmodel中的某个位置完成的。 最好的方法将始终是检查ListBox1.SelectedIndex并且您当然也可以将其绑定到视图模型中,因此您不必真正在其背后的代码中访问它。 在那种情况下,您绝对可以使用事件来命令或类似的操作将SelectionChanged事件绑定回视图模型。

如果您确实喜欢使用示例中提供的代码,则只需将ListBox1.SelectedIndex用于单选择策略,将ListBox1.SelectedItems用于多个选择策略即可。

请有看看这个对这里的情况下更多的细节。 :)

您需要投射数据。 例如使用LINQ

var items = ListBox1.SelectedItems.Cast<collection>();

然后,您可以使用foreach之类的方法遍历它们,或者访问特定的项目,例如

var text1 = items.First().text;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM