I'm trying to add UI elements, written in C# code, to not copy and paste them multiple times in XAML file. I'm using BindableLayout in my XAML file. The problem is that I'm not seeing any element added to that BindableLayout (they're not showing at the screen when I run the app).
.NET MAUI version of this solution is 9.0.
Here is my code - XAML file:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Maui_testy.BindingLayoutTest"
Title="BindingLayoutTest">
<FlexLayout
BindableLayout.ItemsSource="{Binding Letters}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Button
Text="{Binding .}"
/>
</DataTemplate>
</BindableLayout.ItemTemplate>
</FlexLayout>
</ContentPage>
C# file:
using System.ComponentModel;
using System.Diagnostics;
namespace Maui_testy;
public partial class BindingLayoutTest : ContentPage, INotifyPropertyChanged
{
private List<char> letters;
public List <char> Letters
{
get => letters;
set
{
letters = value;
OnPropertyChanged();
}
}
public BindingLayoutTest()
{
InitializeComponent();
BindingContext = this;
this.letters = new List <char>();
for(Int16 i = 65; i < 91; ++ i)
{
Letters.Add((char)i);
}
}
}
Letterslist is not observable. Either you need to initializeLettersbeforeInitializeComponent()gets called andBindingContextgets set (which is discouraged because it fosters bad design) or you need to makeLettersobservable, e.g. by using an ObservableCollection<T> instead of aList<T>.