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
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; }
}