C# Caliburn.Micro 多选

标签 c# wpf caliburn.micro

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

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

然后将此属性的绑定(bind)添加到您的 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>

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

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

关于C# Caliburn.Micro 多选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34575420/

相关文章:

c# - SCardConnect (winscard.dll) 总是返回错误

c# - 如何使用 C# 进行 XSLT 2.0 转换

c# - MVVM 必须使用 DataTemplates 吗?

WPF 文本框 : How to change binding mode default to OneWay?

c# - 在 Listbox 上使用自定义 DataTemplate 时,SelectedItem 绑定(bind)停止工作

c# - Caliburn.Micro 将 VM 设置为继承屏幕时,会覆盖 View 中的标题字段

c# - Caliburn Micro WPF : Message. Attach with guard 属性禁用整个主机控制

c# - 从 "c:\Program Files\Microsoft SQL\...\Backup"以外的路径恢复 MS SQL 数据库

C# 事件处理

wpf - 如何设置 ListView 项目的样式?