In WPF, how do I access the items of a ListView?
I know SelectedValuePa开发者_运维百科th="..."
, but in my ListView it displays 7 columns.
For example there is GridViewColumn
which contains room numbers, I want to put all room number row in list and make this for all column.
WPF handles data sources differently from WinForms. At first, it appears more complicated in WPF because you cannot access the source collection like you are used to in WinForms. However, you will quickly find out WPF makes it more natural to develop against.
In WPF, you want to bind your UI control (e.g. ListView) to a data source. The data source is just a collection in the code-behind of any custom type you want it to be. As long as you grant the appropriate access to the collection, any of your code-behind can access the source data without talking to the ListView.
For list views, the data source will be an ObservableCollection on the DataContext with which your view is wired up to. Type T is a custom class type. Through XAML code, you can define a data template on the ListView that describes how properties on your custom class type are displayed for each data item.
To learn more, research the MVVM UI pattern and study INotifyPropertyChanged interface.
For instance:
Code Behind
internal class MyViewModel
{
public ObservableCollection<Person> People = new ObservableCollection<People>();
// code to populate People
}
public class MyWindow
{
public MyWindow()
{
DataContext = new MyViewModel();
}
}
View
<ListView ItemsSource={Binding Path=People, Mode=OneWay}>
<ListView.DataTemplate>
<Label Content={Binding Path=FirstName, Mode=OneWay} />
<!-- Blah blah blah -->
</ListView.DataTemplate>
</ListView>
This MSDN article goes into detail (see the code snippets and examples at the very bottom).
The cells of the listview are generated by a list of objects, where are several bindings for every column.
What's you are asking for is not the WPF way, but the old-style approach (e.g. winforms). WPF is totally different, and the access to the cells is cumbersome (I'd add not reliable also).
Knowing the object that has been selected, you simply access its properties where the various columns are bound on.
精彩评论