UserControl as DataTemplate inside ListBox

后端 未结 4 1855
北海茫月
北海茫月 2020-12-25 13:48

I want to reuse my UserControls in other UserControls like page or window as DataTemplates, in this example inside a ListBox. Everything is MVVM.

I\'ve a UserControl

4条回答
  •  心在旅途
    2020-12-25 13:58

    I had a similar issue and I fixed it using the below codes. I am posting here so that somebody else might benefit from it.

    Please don't forget to upcast my answer, if it helps you.

    EmpUserControl.xaml file

    
        
            
                
                
            
            
                
                
            
            
            
            
            
        
    
    

    EmpUserControl.xaml.cs

    namespace Sample.UserControls
    {
        /// 
        /// Interaction logic for EmpUserControl.xaml
        /// 
        public partial class EmpUserControl : UserControl
        {
            public EmpUserControl()
            {
                InitializeComponent();
            }
        }
    }
    

    MainWindow.xaml file

    
        
            
                
                    
                        
                    
                
            
        
    
    

    MainWindow.xaml.cs file

    namespace Sample
    {
        /// 
        /// Interaction logic for MainWindow.xaml
        /// 
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
        
            private void LoadEmpListBox(){
                var empList = new List{
                    new EmpViewModel { FirstName = "Rajeev", LastName = "Kumar" },
                    new EmpViewModel { FirstName = "Sita", LastName = "Hedge" },
                    new EmpViewModel { FirstName = "Deepika", LastName = "PL" }
                };
                LbEmp.ItemsSource = empList;
            }
        }
    }
    

    EmpViewModel model

    public class EmpViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    

提交回复
热议问题