Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Winui 3 Combobox in datagrid not displaying data
I am migrating a WPF app to WinUI3. Things went well until I needed to put a combo box in the datagrid. That MS had removed the datagrid from the standard tools was overcome with Community Toolkit Controls.
I can make a column with a combobox, but I have not managed to link it correctly to the data I need to select from. Let's say that it is a page to display books with their primary genre in the combobox.
I use MVVM for connecting the view and data. Showing the main part of the data for the page works. However, the combobox for genres is empty.
The window:
<Grid x:Name="RootGrid">
<ctWUI3:DataGrid x:Name="tasksDataGrid"
AutoGenerateColumns="False"
GridLinesVisibility="All"
CanUserSortColumns="True"
ScrollViewer.VerticalScrollBarVisibility="Auto"
AlternatingRowBackground="LightGray"
ItemsSource="{Binding Books}"
Margin="10,0,5,0"
RowDetailsVisibilityMode="VisibleWhenSelected">
<ctWUI3:DataGrid.Columns>
<ctWUI3:DataGridTextColumn Binding="{Binding Id}"
Header="Name"
Width="150"
IsReadOnly="False" />
<ctWUI3:DataGridTextColumn Binding="{Binding Title}"
Header="Name"
Width="150"
IsReadOnly="False" />
<ctWUI3:DataGridTextColumn Binding="{Binding Description}"
Header="Description"
Width="150"
IsReadOnly="False" />
<ctWUI3:DataGridTextColumn Binding="{Binding PrimaryGenreId}"
Header="Genre"
Width="150"
IsReadOnly="False" />
<ctWUI3:DataGridComboBoxColumn Binding="{Binding PrimaryGenreId}"
Header="Genre"
ItemsSource="{Binding Genres, Mode=OneWay}"
DisplayMemberPath="Name"
Width="SizeToHeader" />
</ctWUI3:DataGrid.Columns>
</ctWUI3:DataGrid>
</Grid>
The xaml.cs
public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
RootGrid.DataContext = new MainViewModel();
}
}
Then the MainViewModel.cs contains two private fields, a constructor of test data, and the public getter/setters for the fields.
public ObservableCollection<Book> Books
{
get => _books;
set { SetProperty(ref _books, value); }
}
public ObservableCollection<Genre> Genres
{
get => _genres;
set { SetProperty(ref _genres, value); }
}
How do I get the combobox to display the genre of the book for that row (using a GenreId field as the foreign key)?
2 comment threads