【问题标题】:Need to get the selected item from Multiple select listbox in silverlight需要从silverlight中的多选列表框中获取所选项目
【发布时间】:2015-08-04 06:27:02
【问题描述】:

我使用以下代码将多选列表框中的值与 silverlight 中的复选框绑定

  <ListBox x:Name="ValListBox" Margin="188,212,136,100" SelectionMode="Multiple">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding RelativeSource={RelativeSource AncestorType=ListBoxItem}, Path=IsSelected}" Content="{Binding}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

我需要使用 c# 获取所选项目的文本吗?

【问题讨论】:

  • 如果你想要 ViewModel,你可以通过将 ListBox 的 SelectedItem 绑定到与 ItemsSource Collection 相同类型的属性来获得它。如果你想在 xaml 中使用它,那么你可以绑定 SelectedItem.Content 属性和 ElementName ValListBox

标签: c# wpf xaml silverlight listbox


【解决方案1】:

通过使用下面的方法,我们可以得到多选列表框中的选中项。

xaml 的变化:我们需要添加 Click Function。

 <ListBox x:Name="ValListBox" Margin="188,212,136,100" SelectionMode="Multiple">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <CheckBox   Click="CheckBox_Click" IsChecked="{Binding RelativeSource={RelativeSource AncestorType=ListBoxItem}, Path=IsSelected}"  Content="{Binding}" />
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox> 

在后面的代码中我们可以得到,

List<string> selecteditems = new List<string>();
 private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            var cb = sender as CheckBox;
            if (cb.IsChecked == true)
            {
                var item = cb.DataContext;
                selecteditems.Add(item.ToString());
            }
            else
            {
                var item = cb.DataContext;
                selecteditems.Remove(item.ToString());
            }
        }

在 selecteditems List 中,我们可以从 Multiple Listbox 中获取所有选定的项目

【讨论】:

    猜你喜欢
    • 2017-06-09
    • 1970-01-01
    • 2014-10-14
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 2012-11-16
    • 2011-09-25
    相关资源
    最近更新 更多