How to use x:Name of items in listView at codebehind?

后端 未结 4 1911
情书的邮戳
情书的邮戳 2021-01-24 10:27

Is there any way to use x:Name of the stacklayout in listview at code behind in xamarin.forms?

 

        
4条回答
  •  心在旅途
    2021-01-24 10:53

    To be able to access templated elements by name and by whatever way you like, create a custom view that will serve You as a cell. And in the cell's code-behind you will be able to access everything by name. Your initial parent list will now look like:

    
     
          
              
         
    
    
    

    Your brand new cell will look like:

    XAML:

       
        
        
            
    
        
    

    Code:

    namespace YourNameSpace
    {
        [XamlCompilation(XamlCompilationOptions.Compile)]
        public partial class MyViewCell
        {
            public MyViewCell()
            {
                InitializeComponent();
    
                //you can init your cells here
                InitCell(); //this is just for demo
            }
    
            public void InitCell()
            {
                //i can access my stack:
                btnStack.BackgroundColor = Color.Red;
                //and even more
                txtEvenMore.Text = "By name? Yes! :)";
            }
    
            //Now not for demo but in the real world:
            //We can set content according to your data from ItemsSource
            //This will act when you set your ListView ItemsSource to something valid
            protected override void OnBindingContextChanged()
            {
                SetupCell();
                base.OnBindingContextChanged();
            }
    
            public void SetupCell()
            {
                //use data from ItemsSource
                var item = BindingContext as YourItemClass;
                if (item == null) return;
    
                txtEvenMore.Text = item.SomeTextProperty;
                //etc.. :)
            }
    
       }
     }
    

    Good luck! :)

提交回复
热议问题