Binding resolution for TemplateBinding fails when value provided by upper Binding #33984
-
|
I have a custom control Collection xaml <CollectionView ItemsSource="{Binding Source={x:Reference ThisPage}, Path=Categories}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="models:ItemCategory">
<controls:Collapser
Label="{Binding Name}"> <!-- THIS CAUSES EXCEPTION -->
...
</controls:Collapser>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>Collapser xaml <ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:....Controls"
x:Class="ToolerMobile.Controls.Collapser">
<ContentView.Resources>
<ControlTemplate x:Key="CollapserControlTemplate">
<VerticalStackLayout>
<HorizontalStackLayout>
<Label
Text="{TemplateBinding Label}"/>
</HorizontalStackLayout>
<ContentPresenter/>
</VerticalStackLayout>
</ControlTemplate>
<Style TargetType="controls:Collapser">
<Setter Property="ControlTemplate" Value="{StaticResource CollapserControlTemplate}"/>
</Style>
</ContentView.Resources>
</ContentView>ItemCategory cs public class ItemCategory: ObservableObject
{
public string Id { get; set; }
public string Name { get; set; }
public ItemCategory[]? Subcategories { get; set; }
}Exception stack |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
|
I would name your property Collapser.LabelText instead of Collapser.Label. Also, I would implement it using C#, no need for XAML: using CommunityToolkit.Maui;
using CommunityToolkit.Maui.Markup;
public partial class Collapser : ContentView
{
[BindableProperty]
public partial string LabelText { get; set; } = string.Empty;
public Collapser()
{
ControlTemplate = new ControlTemplate(
() => new VerticalStackLayout
{
new HorizontalStackLayout { new Label().Bind(Label.TextProperty, (Collapser c) => c.LabelText, source: this) },
new ContentPresenter()
});
}
} |
Beta Was this translation helpful? Give feedback.
-
|
Your stack trace references code you haven’t provided, and without that missing context the issue can’t be reproduced. Using only the code you shared, I was able to build an application that runs without crashing, so the problem is likely in the parts you haven’t included. |
Beta Was this translation helpful? Give feedback.
So turns out changing the BindableProperty to public instead of private fixed the issue. 🤦🏽♂️