How do you add sub-items to a ListView
? I need to generate everything dynamically, but every example I've found uses XAML.
Non-WPF was so simple:
ListViewItem lvi = listview.items.add(wahtever);
lvi. blah blah blah
How do you add sub-items in WPF without using XAML?
As already mentioned, WPF doesn't have sub-items like WinForms. Instead you use properties on an object that suits your purposes.
For completeness, here is XAML contrasted with code.
XAML:
<UniformGrid Columns="2">
<ListView Name="xamlListView">
<ListView.View>
<GridView>
<GridViewColumn Header="X Value" DisplayMemberBinding="{Binding X}"/>
<GridViewColumn Header="Y Value" DisplayMemberBinding="{Binding Y}"/>
</GridView>
</ListView.View>
<ListView.Items>
<PointCollection>
<Point X="10" Y="20"/>
<Point X="20" Y="30"/>
</PointCollection>
</ListView.Items>
</ListView>
<ListView Name="codeListView"/>
</UniformGrid>
Code:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var view = new GridView();
view.Columns.Add(new GridViewColumn { Header = "First Name", DisplayMemberBinding = new Binding("First") });
view.Columns.Add(new GridViewColumn { Header = "Last Name", DisplayMemberBinding = new Binding("Last") });
codeListView.View = view;
codeListView.Items.Add(new { First = "Bill", Last = "Smith" });
codeListView.Items.Add(new { First = "Jane", Last = "Doe" });
}
The "WPF way" would be to bind your listview to a collection that represents the data you want to display. Then add objects containing data to that collection. You almost never should have to deal with adding ListViewItems
to your list manually as you are planning to do. I could come up with an example but there's many threads here on SO already that solve exactly this problem:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With