locked
How to access a named control inside a XAML DataTemplate in Code Behind Page RRS feed

  • Question

  • User152984 posted

    I have a Listview. It contains some controls like Image,Label. When tapping on image I need to perform some action. But i'm unable get the control in Code Behind. I given x:Name to Image control. Please help me. Here the code.

    <ListView ItemsSource="{Binding MedicalLabOrders}" RowHeight = "60" BackgroundColor="LightGray">?           
     <ListView.ItemTemplate>?                         
    <DataTemplate>?                            
    <ViewCell>?                                
    <StackLayout Orientation="Horizontal">?                                    
    <Image x:Name="checkBox" HeightRequest = "20" Source = "check.png" />?                                    
    <Label Text="{Binding Name}" HorizontalOptions="StartAndExpand" VerticalOptions="Center"/>?                                
    </StackLayout>?                            
    </ViewCell>?                        
    </DataTemplate>?            
    </ListView.ItemTemplate>?            
    </ListView>?
    

    How can I access x:Name="checkBox" in Code Behind. I used this.checkBox.Source = "uncheck.png"; in Code Behind. But it's throwing an error Page does not contain a defenation for checkbox.

    Wednesday, March 14, 2018 1:52 PM

All replies

  • User180523 posted

    You don't. Do a search as I'm sure I answered a nearly identical question for this same thing about a week ago.

    The short answer is: * If you're naming controls there is a problem. * By default, they are private from XAML and that's on purpose. * Run-time generated controls in a ListView from ItemTemplate won't get unique names. You can't work of names and shouldn't be working off names. Names are purely for UI and your ViewModel should be UI unaware.

    In summary: Your plan to base logic on the name of controls is so 1997 that you really shouldn't be even trying to work like that. I would urge you to update your strategy to good 2017 patterns and property use of MVVM behavior and expectations.

    Wednesday, March 14, 2018 1:58 PM