Jacek
Jacek

Reputation: 12053

Injection and parameterless constructor in WPF

I have code for user control in WPF (below). I use nInject as IocContainer. I initialize ioc in OnStartup event in my App class.

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        var iocContainer = IocContainer.Get();

        iocContainer.Bind<CreateRemindPopup>().To<CreateRemindPopup>();
        iocContainer.Bind<MainWindow>().To<MainWindow>();

        Current.MainWindow = iocContainer.Get<MainWindow>();
        Current.MainWindow.Show();
    }

If I remove parameterless constructor I get exception NullReferenceException when control should be displayed. When parameterless constructor is present code for display content is not executed.

My question is how can I force WPF to execute constructor with parameter? I don't want to remove parameterless constructor, becouse then I lost designer in VisualStudio.

public partial class RemindersListing : UserControl
{
    private readonly IReminderReadLogic _reminderReadLogic;

    public ObservableCollection<Reminder> Reminders { get; set; }

    public RemindersListing()
    {
    }

    public RemindersListing(IReminderReadLogic reminderReadLogic)
    {
        _reminderReadLogic = reminderReadLogic;
        InitializeComponent();

        var list = _reminderReadLogic.Get();
        Reminders = new ObservableCollection<Reminder>(list);
    }
}

Upvotes: 0

Views: 1599

Answers (1)

Greg Oks
Greg Oks

Reputation: 2730

How about turning the default constructor to private so wpf would call it and adding the constructor with parameters that you wish:

private RemindersListing()
{
    InitializeComponent();
}

public RemindersListing(IReminderReadLogic reminderReadLogic) : this()
{
    ...

}

Or consider using DependencyProperty like in this article:

http://www.informit.com/articles/article.aspx?p=2115888&seqNum=3

Upvotes: 5

Related Questions