Reputation: 479
I've been going nuts trying to find a solution to what seems like a simple problem. I am trying to find a way to Iterate through my ListView and get values.
I have a ListView with bindings which looks like this in xaml (simplified):
<ListView x:Name="MColumnsListXaml" HorizontalAlignment="Left" Height="Auto" Margin="0,42,0,0" VerticalAlignment="Top" Width="Auto">
<ListView.View>
<GridView>
<GridViewColumn Header="First Name" Width="Auto" DisplayMemberBinding="{Binding MColumnName}" />
<GridViewColumn Header="Last Name" Width="Auto" DisplayMemberBinding="{Binding MColumnName2}" />
</GridView>
</ListView.View>
</ListView>
I declare bindings:
public class MandatoryColumns
{
public string MColumnName { get; set; }
public string MColumnName2 { get; set; }
}
Columns are populated by an event trigger which calls a method:
private void btnValidateColumns_Click(object sender, RoutedEventArgs e)
{
MandatoryOptionalColumnsList();
}
public void MandatoryOptionalColumnsList()
{
List<MandatoryColumns> MColumnsList = new List<MandatoryColumns>();
MColumnsList.Add(new MandatoryColumns() { MColumnName = "John", MColumnName2 = "Smith" });
MColumnsList.Add(new MandatoryColumns() { MColumnName = "Jason", MColumnName2 = "Bell" });
MColumnsListXaml.ItemsSource = MColumnsList;
}
Now I need to get information that is in the ListView and that's where I'm stuck. My intention is to extract a column in a ListView and cross check against another list. To get the values, I've tried foreach
loop as per below:
public void test()
{
foreach (var item in MColumnsListXaml.Items)
{
MessageBox.Show(MColumnsListXaml.ToString()); //MColumnsListXaml = {System.Windows.Controls.ListView Items.Count:2}
MessageBox.Show(MColumnsListXaml.Items.ToString()); //MColumnsListXaml.Items = {System.Windows.Controls.ItemCollection}
MessageBox.Show(item.ToString()); //item = {tutorialWpfApplication1.MandatoryColumns}
}
}
In debugger I see item returns object {tutorialWpfApplication1.MandatoryColumns}
and holds my needed information, but I can't find a way to access it. I tried to iterate item
by making it dynamic
, declare ListViewItem
instead of `var and various solutions online, but everything always resulted in an exception error.
Upvotes: 0
Views: 7824
Reputation: 108
If you cast item
to the type MandatoryColumn
you should be able access the values. As long as you know that every item in the list is of that type then you shouldn't get an exception when casting.
Upvotes: 1
Reputation: 11389
After you set the value of ItemsSource
you also can get the value. So you can cast and use the list like
List<MandatoryColumns> items = (List<MandatoryColumns>)MColumnsListXaml.ItemsSource;
foreach (MandatoryColumns item in items)
{
//Do some work with the MandatoryColumns item
}
Upvotes: 3
Reputation: 169160
Try this:
foreach (var item in MColumnsListXaml.Items.OfType<MandatoryColumns>())
{
MessageBox.Show(item.MColumnName);
MessageBox.Show(item.MColumnName2);
}
Upvotes: 5