好的,我知道了。
虽然没什么要做的,但因为我对WPF的所有东西都不熟悉,所以还需要做一些工作。
以下是解决方案:
public class CheckableListViewItem : ListViewItem
{
[Category("Appearance")]
[Bindable(true)]
public bool IsChecked { get; set; }
}
public class CheckableListView : ListView
{
public IList CheckedItems
{
get
{
List<object> CheckedItems = new List<object>();
for (int i=0;i < this.Items.Count; ++i)
{
if ((this.ItemContainerGenerator.ContainerFromIndex(i) as CheckableListViewItem).IsChecked)
CheckedItems.Add(this.Items[i]);
}
return CheckedItems;
}
}
public bool IsChecked(int index)
{
if (index < this.Items.Count) return (this.ItemContainerGenerator.ContainerFromIndex(index) as CheckableListViewItem).IsChecked;
else throw new IndexOutOfRangeException();
}
protected override bool IsItemItsOwnContainerOverride(object item)
{
if (item is CheckableListViewItem) return true;
else return false;
}
protected override DependencyObject GetContainerForItemOverride()
{
return new CheckableListViewItem();
}
}
在Window.Resources(clr=my class namespace)下插入XAML:
<DataTemplate x:Key="CheckBoxCell">
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding Path=IsChecked,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type clr:CheckableListViewItem}}}" />
</StackPanel>
</DataTemplate>
作为您的CheckableListView:
<clr:CheckableListView SelectionMode="Single" [...] >
<ListView.View>
<GridView>
<GridViewColumn CellTemplate="{StaticResource CheckBoxCell}"
Width="30"/>
[...]
</GridView>
</ListView.View>
</clr:CheckableListView>