ARTICLE AD BOX
I am using a WPF DataGrid with MVVM approach. The ItemsSource of the DataGrid is bound to an ObservableCollection of something which has an Id and an ObservableCollection of strings.
I want the Id to shown in the DataGrid row and the collection of strings should be displayed in the dow details. Furthermore I need to select of the strings, to let's say remove it. So I added a ListBox to the row details.
The ItemsSource and SelectedItem of the DataGrid are working fine and so is the ItemsSource of the ListBox in the row details. But the SelectedItem of the ListBox is not set, when I click an item.
This is my XAML code:
<Window x:Class="DataGridTestApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:DataGridTestApp" Title="MainWindow" Height="450" Width="800"> <DataGrid ItemsSource="{Binding Entries}" SelectedItem="{Binding SelectedEntry}" x:Name="dataGrid" AutoGenerateColumns="False" RowDetailsVisibilityMode="Visible"> <DataGrid.Columns> <DataGridTextColumn Header="Id" Binding="{Binding Id}" Width="80"/> </DataGrid.Columns> <DataGrid.RowDetailsTemplate> <DataTemplate> <ListBox ItemsSource="{Binding Comments}" SelectedItem="{Binding SelectedComment}"/> </DataTemplate> </DataGrid.RowDetailsTemplate> </DataGrid> </Window>And this is the code behind:
using System.Collections.ObjectModel; using System.Windows; namespace DataGridTestApp; public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); var gridVM = new GridViewModel(); for (int i = 0; i < 3; i++) { var entryVM = new EntryViewModel { Id = $"Id {i}" }; for (int j = 0; j < 3; j++) entryVM.Comments.Add($"Comment {(i * 3) + j}"); gridVM.Entries.Add(entryVM); } dataGrid.DataContext = gridVM; } } public class GridViewModel { public ObservableCollection<EntryViewModel> Entries { get; } = []; public EntryViewModel? SelectedEntry { get; set; } } public class EntryViewModel { public string Id { get; set; } = string.Empty; public ObservableCollection<string> Comments { get; } = []; public string? SelectedComment { get; set; } }I am setting a breakpoint at the setter of SelectedEntry and the setter of SelectedComment. The first one is called, but not the second one. What am I missing?
Thanks in advance, wolfoe
