How to bind data properly to user control if it's inside a ListView's DataTemplate?

Sunshine 46 Reputation points
2023-05-08T07:29:30.6033333+00:00

Hello everyone,

In MAUI, as instructed by ContentView doc, we can define user controls for reusability.

However, since it requires specifying Source when binding, I don't know how to bind data for it if it is inside a DataTemplate of ListView.

 

Here is the link of [demo project](https://github.com/SunshineSpring666/UserControlInListView"demo project") .  Thanks.

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,866 questions
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 68,491 Reputation points Microsoft Vendor
    2023-05-09T02:08:17.91+00:00

    Hello,

    You can do this by moving BindingContext="{x:Reference thisUC}" to the <Stacklayout> and no need to set Reference for Label's binding property again, you can refer to following xaml code.

    <ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                   x:Name="thisUC"         
                 x:Class="MauiApp2.CardView">
        <StackLayout  BindingContext="{x:Reference thisUC}" >
            <Label Text="{Binding CardTitle}" FontSize="20" BackgroundColor="Gray" Margin="5"/>
        </StackLayout>
    </ContentView>
    
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful