views:

126

answers:

1

Hello,

this I got: A first chance exception of type 'System.NullReferenceException' occurred in PresentationFramework.dll

When I use a parameter for the constructor of my LessonPlannerViewModel class.

I use a datatemplateselector class to switch between weekly/daily view.

public class ApplicationNavigationTemplateSelector : DataTemplateSelector
{
    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        if (item is LessonPlannerViewModel)
        {
            var vm = item as LessonPlannerViewModel;
            Window window = Application.Current.MainWindow;                

            if (vm.IsDailyView)
                return window.FindResource("dailyViewTemplate") as DataTemplate;
            else
                return window.FindResource("weeklyViewTemplate") as DataTemplate;
        }
        return base.SelectTemplate(item, container);
    } 
}

public LessonPlannerViewModel(DateTime asOfDate)
    {
        _asOfDate = asOfDate;

        if(_isDailyView) 
            LoadDailyData();
        if(_isWeeklyView)
            LoadWeeklyData();

...

Is that not allowed? Without the parameter I get no exception...

What do I wrong?

EDIT: NOw I changed the parameter to an integer and got better message ;P

XamlParseException=> 'No matching constructor found on type 'TBM.ViewModel.LessonPlannerViewModel'. You can use the Arguments or FactoryMethod directives to construct this type.' Line number '13' and line position '10'.

ok this is now understandable, that

<UserControl.Resources>
    <ViewModel:LessonPlannerViewModel x:Key="LessonPlannerViewModelID" />
</UserControl.Resources>

has no parameter.

So what to do now?

A: 

You could use a mediator pattern to send the data to the viewmodel after its initialization. (Using a viewmodel constructor without any parameters)

I use the MVVM Light ToolKit of Laurent Bugnion. A really nice, light framework for mvvm. This includes a mediator called Messenger

Otherwise you will find many sources for the mediator pattern: Google Search mvvm mediator

CodeWeasel
I already use laurent`s framework. But I saw my loading strategy needs to change like running a Init method to load data when the class object is created.
msfanboy
I made that experience too, its best to ceep the constructor clean or just register for messages. You can use an abstract base class with abstract methods for initialization, activation, reset, refresh and viewmodel actions like that.
CodeWeasel
ah who cares... ich akzeptier das als Antwort XD
msfanboy