开发者

NInject: Send parameter to ViewModel Class Constructor

开发者 https://www.devze.com 2023-03-22 06:25 出处:网络
I am developing a Windows Phone 7 app and am using the MVVM pattern. I have a need to pass a parameter to the contructor of the ViewModel for a page. All my datac开发者_如何学JAVAontexts and binding a

I am developing a Windows Phone 7 app and am using the MVVM pattern. I have a need to pass a parameter to the contructor of the ViewModel for a page. All my datac开发者_如何学JAVAontexts and binding are done in XAML. Through my research I've seen that I need to do so using a dependency injector such as NInject.

Here's a little detail on whats going on: I have a page with a ListPicker that lists various tasks. Each task has a unique TaskID. When an item is selected I need to open another page that will show the selected Tasks detail. My ViewModel and binding is all done and works if I use a static TaskID in the ViewModel but of course I need to use a variable.

I've setup NInject in the project and the various classes needed such as ViewModelLocator and my NInjectModule as shown here:

public class LighthouseNInjectModule : NinjectModule
{
    public override void Load()
    {
        this.Bind<TaskViewModel>().ToSelf().WithConstructorArgument("TaskID", 2690);
    }
}

Note that I have hardcoded a TaskID here and using this code this value properly gets injected into my constructor. Of course, this is hardcoded and I need to get the TaskID for the selected ListPicker item. I know how to get the selected ID from the ListPicker but how do I make NInject aware of it so when my class constructor is run it will have the correct value?

Here is the basic definition of my ViewModel class showing use of the Injector attribute.

public class TaskViewModel : INotifyPropertyChanged
{
    [Inject]
    public TaskViewModel(int TaskID)
    {
        //run function to get data using TaskID
    }
}


WithConstructorArgument has another oveload that accepts a lazy evaluated Func<Context, object>.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号