2010-05-05 74 views
2

我已經閱讀了很多關於使用與IsSelected綁定的複選框來擴展ListView的例子。但我想要更多。WPF - 使用可選和可選ListViewItems擴展ListView

我想檢查和選擇狀態之間的分離,所以我得到一個ListBox有一個選定的項目,但可以有多個檢查項目。 不幸的是,ListViewItem沒有檢查屬性,我看不到有可能使ListView與自定義的CheckableListViewItem一起工作。

當然,我可以使用具有checked屬性的對象列表作爲ItemSource,但我不認爲這是一個好方法。檢查與否是列表或項目容器的問題,而不是其中列出的對象。除此之外,我不希望所有的類像用戶,角色,組都有類似checkableUser,checkableRole和checkableGroup的對應類。

我想要的行爲可以easyly accomblished的UI與

<DataTemplate x:Key="CheckBoxCell"> 
    <StackPanel Orientation="Horizontal"> 
     <CheckBox /> 
    </StackPanel> 
</DataTemplate> 

<GridViewColumn CellTemplate="{StaticResource CheckBoxCell}" Width="30"/> 

但是,如果沒有上的複選框,如果它被選中與否我不能檢查結合。

有什麼辦法可以完成這樣的事情嗎?對我來說完美的解決方案將是有listView1.SelectedItem,listView1.CheckedItems和可能的listView1.UncheckedItems和當然listView1.CheckItem和listView1.UncheckItem。

感謝您的任何幫助。

回答

4

好的,我明白了。 沒有太多的事情要做,但因爲我是新來的整個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(); 
    } 
} 

插入到你的XAML下Window.Resources(CLR =我的類的命名空間):

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

也許這可以幫助有同樣問題的人。

1

爲了做到這一點,您必須創建自定義ListBox和自定義ListBoxItem控件以在您的應用程序中使用。否則,您將不得不將其添加到列表中的項目中作爲通用對象ICheckable<T>(其中T是用戶或角色),並且您的項目具有ICheckableCollection<ICheckable<T>>,而不是向模型對象添加可檢查項。

+0

只是爲了正確,即時通訊談論ListView和ListViewItem,但它幾乎相同。你的海關課程權利,我認爲它不會那麼複雜。但是爲了創建一個ListView.CheckedItems,我需要遍歷容器來查找已檢查的容器,而我沒有辦法做到這一點。遍歷項目並使用GetContainerForItem僅適用於DependencyObject類型的項目。任何線索? – Marks 2010-05-06 09:17:43