C#Caliburn.Micro多项选择

时间:2016-01-03 10:17:08

标签: c# wpf caliburn.micro

我在我的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;
}

1 个答案:

答案 0 :(得分:1)

将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:

<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;           
        }
    }