I have a C# WPF application and using ListView with basically works fine. My issue is: I want to preselect items in the list view. The selection should be visible for the user, and the user should be able to modify the selection.
I tried prototyping with a very simple application.
Here ist my XAML Code:
<Grid>
<ListView Name="lvEntries" SelectionMode="Multiple" Margin="0,0,0,116">
<ListView.View>
<GridView>
<GridViewColumn Width="100" Header="Lastname" DisplayMemberBinding="{Binding LastName}"/>
<GridViewColumn Width="100" Header="Firstname" DisplayMemberBinding="{Binding FirstName}"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
And here my code-behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
lvEntries.Items.Clear();
Person newPerson = new Person();
newPerson.FirstName = "Jack";
newPerson.LastName = "Nicholson";
lvEntries.Items.Add(newPerson);
Person newPerson2 = new Person();
newPerson2.FirstName = "Bill";
newPerson2.LastName = "Murray";
lvEntries.Items.Add(newPerson2);
}
}
public class Person
{
public string LastName { get; set; }
public string FirstName { get; set; }
}
Everything fine so far. Now i would like to make a pre-selection. The ListViewItem Class has a .IsSelected property, which can be theoretically set in code-behind. But
lvEntries.Items[0].IsSelected = true;
or
newPerson.IsSelected = true;
is not available.
Then i tried to derive the class "Person" from ListViewItem - now .IsSelected is available. Now the C# code looks like:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
lvEntries.Items.Clear();
Person newPerson = new Person();
newPerson.FirstName = "Jack";
newPerson.LastName = "Nicholson";
newPerson.IsSelected = true;
lvEntries.Items.Add(newPerson);
Person newPerson2 = new Person();
newPerson2.FirstName = "Bill";
newPerson2.LastName = "Murray";
newPerson2.IsSelected = true;
lvEntries.Items.Add(newPerson2);
}
}
public class Person : ListViewItem
{
public string LastName { get; set; }
public string FirstName { get; set; }
}
The result is funny: I can see the selected lines after starting the app. But the lines does not have content ;-) they are empty...
I think i make something basically wrong.
Is there a simple way to make a selection in a ListView with the C# code (Code-Behind) ?
Thank you very much in advance! Emil
I would add
IsSelectedto the item itself. And since it seems that you also want to change which item is selected, you should also make it observable.In this sample code, I'm using the CommunityToolkit.Mvvm NuGet package and creating ViewModels with it.
PersonViewModel.cs
MainViewModel.cs
MainWindow.xaml