从列表框中只获取一个选定项目

时间:2016-01-08 06:43:54

标签: c# .net wpf listbox viewmodel

我正在使用wpf中的Listbox。我的问题是我只从listbox中获取一个选定项目。我想获取所有选中但不知道如何实现的项目?请帮忙! 这是我的代码:

<ListBox ItemsSource="{Binding Markets}" BorderThickness="0" Background="{x:Null}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionMode="Multiple" SelectedItem="{Binding SelectedItem}">
     <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel IsItemsHost="True" />
            </ItemsPanelTemplate>
     </ListBox.ItemsPanel>
     <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Content="{Binding}" Style="{DynamicResource CheckBoxStyle1}" Width="140" Margin="10"/>
            </DataTemplate>
     </ListBox.ItemTemplate>
</ListBox>

这是我的viewmodel内容:

    private string _selectedItem;
    public List<string> Markets { get; set;}
    public SettingVM()
    {

        Markets = new List<string>();
        Markets.Add("United Kingdom");
        Markets.Add("Australia");
    }
    public string SelectedItem
    {
        get
        {
            return _selectedItem;
        }
        set
        {
            Set(() => SelectedItem, ref _selectedItem, value);
        }
    }     

5 个答案:

答案 0 :(得分:1)

您可以直接将SelectedItem listobx属性绑定到视图模型,但不能绑定SelectedItems属性。

我使用了一种行为来实现与委托命令相关联的行为(包含在Prism框架中)

你的对象

class MyObject
{

}

行为

internal class MyObjectSelectionChangedToCommand
{

    public static readonly DependencyProperty SelectionCommandProperty =
        DependencyProperty.RegisterAttached("SelectionCommand", typeof(DelegateCommand<GridSelectionInfo<MyObject>>),
        typeof(ResourceCardGridSelectionChangedToCommand), new PropertyMetadata(null, OnSelectionCommandChanged));

    public static DelegateCommand<GridSelectionInfo<MyObject>> GetSelectionCommand(DependencyObject obj)
    {
        return (DelegateCommand<GridSelectionInfo<MyObject>>)obj.GetValue(SelectionCommandProperty);
    }

    public static void SetSelectionCommand(DependencyObject obj, DelegateCommand<GridSelectionInfo<MyObject>> value)
    {
        obj.SetValue(SelectionCommandProperty, value);
    }

    private static void dg_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var tsci = new GridSelectionInfo<MyObject>
        {
            Added = e.AddedItems.Cast<MyObject>().ToList(),
            Removed = e.RemovedItems.Cast<MyObject>().ToList(),
            Selected = ((ListBox)sender).SelectedItems.Cast<MyObject>().ToList()
        };

        var cmd = GetSelectionCommand((DependencyObject)sender);
        cmd.Execute(tsci);
    }

    private static void OnSelectionCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var dg = d as ListBox;

        if (dg != null) dg.SelectionChanged += dg_SelectionChanged;
    }
}

public class GridSelectionInfo<T>
{
    public GridSelectionInfo()
    {
        Selected = new List<T>();
        Added = new List<T>();
        Removed = new List<T>();
    }

    public List<T> Added { get; set; }

    public List<T> Removed { get; set; }
    public List<T> Selected { get; set; }

    public override string ToString()
    {
        return string.Format("Added: {0}, Removed: {1}, Selected: {2}", Added.Count, Removed.Count, Selected.ToFormattedString());
    }
}

将视图模型命令绑定到行为

的XAML部分
<ListBox  ItemsSource="{Binding MyCollection}"
 resources:ResourceCardGridSelectionChangedToCommand.SelectionCommand="{Binding CmdObjectSelectionChanged}">
</ListBox>

然后,在您查看模型时,您只需要声明命令

public DelegateCommand<GridSelectionInfo<MyObject>> CmdObjectSelectionChanged { get; private set; }

创造它

CmdObjectSelectionChanged = new DelegateCommand<<GridSelectionInfo<MyObject>>(ExecuteSelect,CanExecuteSelect);

因此,每次选择在列表框中更改时,您将收到包含在GridSelectionInfo对象中的执行委托中所选项目的所有信息;

答案 1 :(得分:0)

也许这可以帮到你

您可以在ListBox.SelectedItems中找到它们。使用foreach

foreach (ListItem li in listBox1.SelectedItems)
{
// your code here
}

答案 2 :(得分:0)

您使用&#34; SelectedItem =&#34; {Binding SelectedItem}&#34;&gt;&#34;。根据MSDN&#34;获取或设置当前选择中的第一个项目,如果选择为空,则返回null&#34;

您需要将SelectedItems绑定到viewmodel中的列表。

答案 3 :(得分:0)

在ListBox控件中,SelectedItems属性是只读的,但您可以添加执行该作业的行为,请参阅以下答案:https://stackoverflow.com/a/8369532/1431524

答案 4 :(得分:0)

我遇到了同样的问题,当我绑定到SelectedItems时,属性在某些情况下没有通知模型!我结束了使用非持久化属性(&#34; Selected&#34;)扩展我的实体,然后将此属性绑定到CheckBox的IsCheched属性。 在你的情况下,创建另一个部分类文件Market来扩展Market对象,添加一个新的bool属性(例如Selected),然后在你的复选框中绑定这个属性:

<CheckBox Content="{Binding}" IsChecked="{Binding Selected}" Style="{DynamicResource CheckBoxStyle1}" Width="140" Margin="10"/>