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