2010-09-10 74 views
0

用戶選擇了一個包含文件的文件夾。我正在做一個listview顯示所選文件夾中的文件。我想顯示每個文件包含的內容,但是我想在用戶從listviewitem檢查文件時顯示它。我正在使用以下代碼:如何檢查列表視圖項是否被選中

if (listView1.Items[0].Checked == true) 
{ 
    //.... 
} 

它爲什麼不起作用?我應該如何使用數據,例如:

button1.Click(...)button2.Click(...)

+1

哪個「ListView」? Web窗體? Windows窗體? WPF? SilverLight的? – 2010-09-10 20:56:21

+1

也考慮'如果(listView1.Items [0] .Checked)' – 2010-09-10 20:56:42

+1

luc,當發佈一個問題時,它有助於包括錯誤消息或至少更多的細節,至於什麼「不工作」 – NotMe 2010-09-10 20:56:47

回答

1

哪個ev你在捕捉?請記住,如果它是ItemCheck,那麼如果該項目被選中/未選中,則不能使用listView1.Item[0].Checked。您需要採取ItemCheckEventArgs參數,並使用e.Index,檢查整個listview元素時排除該元素。使用e.NewValue分別評估引發ItemCheck事件的項目。

3

不知道你尋找什麼,但也有一些方法來確定其在ListView項目進行檢查:

// This loops through only the checked items in the ListView. 
foreach (ListViewItem checkedItem in listView1.CheckedItems) { 
    // All these ListViewItems are checked, do something... 
} 

// This loops through all the items in the ListView and tests if each is checked. 
foreach (ListViewItem item in listView1.Items) { 
    if (item.Checked) { 
     // This ListViewItem is Checked, do something... 
    } 
} 

可以使用ListViewItem類檢查每個選項的細節。

0

我會創建一個不錯的MVVM設計。 ViewModel將有一個ObservableCollection FileList,其中File可以容納任何你想要的信息。這個類還有一個IsFileSelectedUI屬性,以便你可以在你的代碼中正確使用。然後,在XAML東西很容易:

<ScrollViewer Grid.Column="0" Grid.Row="1" > 
<ItemsControl ItemsSource="{Binding FileList}"> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <Border BorderBrush="Gray" BorderThickness="1" Margin="2" Padding="2"> 
       <StackPanel Orientation="Horizontal"> 
        <CheckBox IsChecked="{Binding IsFileSelectedUI , Mode=TwoWay}"/> 
        <TextBlock Text="{Binding FileName}"/> 
       </StackPanel> 
      </Border> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

然後事情一樣簡單:

FileList.Where(文件=> file.IsFileSelectedUI) 等

如果我理解你說的話:)

+0

這不是一個錯誤的WPF設計,但它不回答OP的問題,這是您如何確定.NET Framework ListView中的項目是否被選中的問題... – 2010-09-10 23:48:37