Connecting ViewModel to a View in Silverlight

I see two ways to connect ViewModel to a view. One of them is in XAML, and the other is depending on the injection in the code.

Which method is more preferable? I prefer the xaml method because I don’t want any code in the code at all, but are there any problems with this other?

<navigation:Page x:Class="MyNamespace.MyViewModel" 
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:ViewModel="clr-namespace:MyNameSpace.MyViewModel"
   xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
   Title="ViewModel Page" >

    <navigation:Page.Resources>
        <ViewModel:MyViewModel x:Key="ViewModel"></ViewModel:MyViewModel>
    </navigation:Page.Resources>

    <Grid x:Name="LayoutRoot" Background="White" 
          DataContext="{StaticResource ViewModel}">

    </Grid>
</navigation:Page>

OR

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

namespace MyNamespace
{
    public partial class MyView : Page
    {
        public MyView()
        {
            InitializeComponent(MyViewModel viewModel);

            this.DataContext = viewModel;
        }
    }
}
+5
source share
4 answers

Shawn View ViewModel. XAML Blendability (. Blend), , . .

Shawn Marriage (. ).

-Erik

+3

I, "", MVVM. , V VM, VM V, Screen . V VM, . . Screen :

    public CatalogItemScreen(IUnityContainer container) : base(container)
    {
        this.ViewModel = Container.Resolve<ICatalogItemViewModel>();
        this.View = Container.Resolve<CatalogItemView>();
        this.View.DataContext = this.ViewModel;
    }

, , V, 2 . Unity Prism, .

+4

, XAML. DataContext. , Microsoft CAG WPF.

0

, View. Justin Angel :

public partial class Page : UserControl
{
    private PageViewModel _viewModel = new PageViewModel();

    public PageViewModel ViewModel
    {
        get { return _viewModel; }
        set { _viewModel = value; }
    } 

    public Page()
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(Page_Loaded);
    }

    void Page_Loaded(object sender, RoutedEventArgs e)
    {
        this.DataContext = ViewModel;
    }

}

I found his post very useful for exploring the complexities of testing MVVM environments.

http://silverlight.net/blogs/justinangel/archive/2009/02/25/silverlight-unit-testing-rhinomocks-unity-and-resharper.aspx

0
source

All Articles