加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#Caliburn.Micro多项选择

发布时间:2020-12-16 07:15:08 所属栏目:百科 来源:网络整理
导读:我在我的C# WPF项目中使用Caliburn.Micro,并且我在ListBox中成功使用了单选选项.如何在此方案中使用多个选择? XAML: ListBox x:Name="Items" ListBox.ItemTemplate DataTemplate StackPanel Orientation="Horizontal" Label Content="{Binding Time}"/ Lab
我在我的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:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读