question

RajuGadda-8585 avatar image
0 Votes"
RajuGadda-8585 asked LeonLu-MSFT answered

I am not able to access x:Name of lable controls in ListView in XAML and Code behind

I have a ListView in Xamarin forms which has a Viewcell in it. The Viewcell contains an lable control with a x:Name attribute. Now I tried to x:name in code behind but it is showing compile time error(The x:name does not exists in current context).
The below code im using.

                 <ListView x:Name="UnPaidInvoicesList" SeparatorVisibility="None" IsPullToRefreshEnabled="True"
                      HasUnevenRows="True"                    
                       ItemSelected="UnPaidInvoicesList_ItemSelected" 
                       VerticalOptions="FillAndExpand">
                     <ListView.ItemTemplate>
                        <DataTemplate>
                           <ViewCell >
                    <StackLayout x:Name="stkDuedate" Orientation="Horizontal">
                        <Label x:Name="lblDueDate1" Text="Due Date:" TextColor="Gray" />
                             <Label x:Name="lblDueDate"  TextColor="{StaticResource Pink}" />
                                                     </StackLayout>
   
                             </ViewCell>
                         </DataTemplate>
                     </ListView.ItemTemplate>
                 </ListView>

Please help on this.



dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

LeonLu-MSFT avatar image
0 Votes"
LeonLu-MSFT answered

Hello,​


Those Labels(named lblDueDate1, lblDueDate) are in <DataTemplate>. You cannot access templated elements by name.

If you have a <Label> on your <Page> and set it an x:Name myLabelTest in XAML,

The XAML compiler creates a variable named myLabel that you can use to reference that control from your code behind.

But if you have a ListView that has two Labels in it's <DataTemplate>, there may be 0, or 10, or 100 copies of that Label generated at runtime depending on the number of items in your ItemsSource.
You cannot refer to it by name because it is not a single, it is changing at runtime.

You can use Listview‘s databinding to binding your properties in your listview to your ViewModel. You can update your value of properties in viewModel at runtime, then your label in listview will be changed.


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.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.