开发者

how to check if listview item is checked

开发者 https://www.devze.com 2023-01-15 10:55 出处:网络
User chose a folder containing files. I\'m making a listview displaying the files in the chosen folder. I want to display what each file contains, but i want to display it when the user checks a file

User chose a folder containing files. I'm making a listview displaying the files in the chosen folder. I want to display what each file contains, but i want to display it when the user checks a file from listviewitem. I'm开发者_Python百科 using the following code:

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

Why doesn't it work? What should i want to use data from for example:

button1.Click(...) to button2.Click(...)?


Not sure exactly what you're looking for but there are a number ways to determine which items in a ListView are checked:

// 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...
    }
}

You can use the ListViewItem Class to examine the details of each selected item.


Which event are you capturing? Remember if it's the ItemCheck, that you cannot use the listView1.Item[0].Checked if that item was what was checked/unchecked. You need to take the ItemCheckEventArgs parameter, and using the e.Index, exclude that element when checking the entire listview elements. Use e.NewValue to separately evaluate the item that raised the ItemCheck event.


I would create a nice MVVM design. The ViewModel would have an ObservableCollection FileList, where File would hold whatever information you want. This class would have also an IsFileSelectedUI property so that you could right in your code. Then in XAML things are easy:

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

Then things are just as easy as:

FileList.Where(file=>file.IsFileSelectedUI) etc

If I understood what you said :)

0

精彩评论

暂无评论...
验证码 换一张
取 消