-1

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

1
  • Try to set ListView's SelectedIndex or SelectedItem property. Commented Oct 13, 2023 at 0:08

2 Answers 2

1

I would add IsSelected to 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

using CommunityToolkit.Mvvm.ComponentModel;

namespace WpfListViewExample;

// The CommunityToolkit's source generators will create 
// UI-interactive properties "FirstName", "LastName" and "IsSelected" for you.
// Don't forget to make this class 'partial'.
public partial class PersonViewModel : ObservableObject
{
    [ObservableProperty]
    private string _firstName = string.Empty;

    [ObservableProperty]
    private string _lastName = string.Empty;

    [ObservableProperty]
    private bool _isSelected;
}

MainViewModel.cs

using CommunityToolkit.Mvvm.ComponentModel;
using System.Collections.ObjectModel;

namespace WpfListViewExample;

public class MainViewModel : ObservableObject
{
    public MainViewModel()
    {
        // The Smiths are selected by default.
        People.Add(new PersonViewModel { FirstName = "John", LastName = "Doe" });
        People.Add(new PersonViewModel { FirstName = "Jane", LastName = "Doe" });
        People.Add(
            new PersonViewModel
            {
                FirstName = "John",
                LastName = "Smith",
                IsSelected = true,
            });
        People.Add(
            new PersonViewModel
            {
                FirstName = "Jane",
                LastName = "Smith",
                IsSelected = true,
            });
        People.Add(new PersonViewModel { FirstName = "John", LastName = "Jones" });
        People.Add(new PersonViewModel { FirstName = "Jane", LastName = "Jones" });
        People.Add(new PersonViewModel { FirstName = "John", LastName = "Williams" });
        People.Add(new PersonViewModel { FirstName = "Jane", LastName = "Williams" });
    }

    public ObservableCollection<PersonViewModel> People { get; } = new();
}

MainWindow.xaml

<Window
    x:Class="WpfListViewExample.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:WpfListViewExample"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Title="MainWindow"
    Width="800"
    Height="450"
    Topmost="True"
    mc:Ignorable="d">

    <Window.DataContext>
        <local:MainViewModel />
    </Window.DataContext>

    <Grid>
        <ListView
            ItemsSource="{Binding People}"
            SelectionMode="Multiple">
            <ListView.View>
                <GridView>
                    <GridViewColumn
                        Width="100"
                        DisplayMemberBinding="{Binding LastName}"
                        Header="Lastname" />
                    <GridViewColumn
                        Width="100"
                        DisplayMemberBinding="{Binding FirstName}"
                        Header="Firstname" />
                </GridView>
            </ListView.View>
            <ListView.ItemContainerStyle>
                <Style TargetType="ListViewItem">
                    <Setter Property="IsSelected" Value="{Binding IsSelected}" />
                </Style>
            </ListView.ItemContainerStyle>
        </ListView>
    </Grid>
</Window>
Sign up to request clarification or add additional context in comments.

Comments

0

In the meanwhile I solved it using the .SelectedItems property of ListView. I simply used the ...SelectedItems.Add(..) method to add the items I want to be selected.

I made the MainWindow accessible for the ViewModel Class using a global variable. Nevertheless I think using the IsSelected property would be more elegant, but it works fine with ...SelectedItems.Add and the effort is okay.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.