C# Caliburn.Micro 多选

C# Caliburn.Micro Multiple selection

我在我的 C# WPF 项目中使用 Caliburn.Micro,并且我在 ListBox 中成功地使用了单选绑定。在这种情况下如何使用多选?

Xaml:

<ListBox x:Name="Items">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Label Content="{Binding Time}"/>
                    <Label Content="{Binding Desc}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

代码:

public BindableCollection<MyObject> Items
{
    get
    {
        var collection = new BindableCollection<MyObject>(_MyObject);
        return collection;
    }
}

public MyObject SelectedItem
{
    get; set;
}

将 IsSelected 属性 添加到您的项目:

public class MyObject : PropertyChangedBase
{
    public DateTime Time { get; set; }
    public String Desc { get; set; }

    bool _isSelected;
    public bool IsSelected
    {
        get { return _isSelected; }
        set
        {
            _isSelected = value;
            NotifyOfPropertyChange();
        }
    }
}

然后将此 属性 的绑定添加到您的列表框:

<ListBox x:Name="Items" SelectionMode="Multiple">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Label Content="{Binding Time}"/>
                    <Label Content="{Binding Desc}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
                <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>

之后您可以在视图模型中引用选定的项目:

    BindableCollection<MyObject> _items = new BindableCollection<MyObject>();
    public BindableCollection<MyObject> Items
    {
        get
        {
            return _items;
        }
    }    

    public BindableCollection<MyObject> SelectedItems
    {
        get
        {
            _selectedItems.Clear();
            _selectedItems.AddRange(Items.Where(mo => mo.IsSelected));
            return _selectedItems;           
        }
    }