Hello i have a problem with dependency injection in WPF application. Here is my code: App.xaml.cs:
IUnityContainer container = new UnityContainer();
container.RegisterType<ICarViewModel, CarViewModel>();
container.RegisterType<MainWindow>();
MainWindow mainWindow = container.Resolve<MainWindow>();
mainWindow.Show();
CarViewModel.cs:
public ObservableCollection<Car> Cars{ get; } = new ObservableCollection<Car>()
{
new Car() {Name = "Audi"},
new Car() {Name = "Peugeot"},
new Car() {Name = "Renault"},
};
CarView.cs:
public partial class CarView : UserControl, ICarView
{
public CarView()
{
InitializeComponent();
}
public CarView(CarViewModel carViewModel) : this()
{
DataContext = carViewModel;
}
}
CarView.xaml:
<ItemsControl ItemsSource = "{Binding Path = Cars}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation = "Horizontal">
<TextBlock Text = "{Binding Path = Name, Mode = OneWay}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
MainWindow.xaml:
<view:CarView x:Name = "CarViewControl"></view:CarView>
Unity container still call only constructor without parameters from CarView. Thanks for advice
InitializeComponent()to the constructor that takes parameters and remove the:this()call and you should be fine.