开发者

MEF Importing ViewModel that needs data, to View for Silverlight

开发者 https://www.devze.com 2023-03-18 04:35 出处:网络
I\'m not sure the best way to get this accomplished. Here\'s my view: public partial class MyPage : Page

I'm not sure the best way to get this accomplished. Here's my view:

public partial class MyPage : Page
{
    [Import]
    public MyVM ViewModel
    {
        get { return DataContext as MyVM ; }
        set { DataContext = value; }
    }

    public String EventName { get; set; }
    public MyPage()
    {
        InitializeComponent();
        CompositionInitializer.SatisfyImports(this);
    }

    // Executes when the user navigates to this page.
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {       }
}

And my VM:

[Export]
public class MyVM : ViewModelBase
{
    public MyVM ()
    {

    }
}

This works great. However, I need to get data from either the viewmodel that has my string, or the URL. Either way, I'm not sure the best way 开发者_如何学Goto get the string to MyVW using MEF. I thought ok I'll use Messaging from MVVMLight, but the MyVM class isn't instantiated yet to receive the broadcast from the other ViewModel. So then I thought well, I'll try this:

[Export]
public class MyVM : ViewModelBase
{
    public MyVM ([Import("hello")]string hello)
    {

    }
} 

and then put this in the view:

[Export("hello")]
public String MyHello { get; set; }

but that gave me an error. Cannot call SatisfyImports on a object of type 'Form A' because it is marked with one or more ExportAttributes.

So what's the best way to accomplish this?


To share data between views I usually inject a SharedData object into my ViewModels.

 [Import(RequiredCreationPolicy = CreationPolicy.Shared)]
 public ISharedData SharedData { get; set; }

I'm also using the Caliburn Micro framework so I'm not passing data around via the URL querystring. By convention CM will parse out URL parameters and inject them into properties on your VM but I'm not sure if this functionality only applies to Windows Phone development.

from here

Examine the Page’s QueryString. Look for properties on the VM that match the QueryString parameters and inject them, performing the necessary type coercion.

When you say you want to possibly pass data from the view to the vm, that should happen through databinding.

0

精彩评论

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