i am having some troubles applying the MVVM pattern, for start i am following this example to learn how to apply and use the pattern…
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
So my problem is establishing the “connection” between the View with the ViewModel…
In the example we have a View with a CollectionViewSource where the Source is the AllCustomers property:
<UserControl
x:Class="DemoApp.View.AllCustomersView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase">
<UserControl.Resources>
<CollectionViewSource x:Key="CustomerGroups" Source="{Binding Path=AllCustomers}"/>
</UserControl.Resources>
<DockPanel>
<ListView AlternationCount="2" DataContext="{StaticResource CustomerGroups}" ItemsSource="{Binding}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=DisplayName}"/>
<GridViewColumn Header="E-mail" DisplayMemberBinding="{Binding Path=Email}"/>
</GridView>
</ListView.View>
</ListView>
</DockPanel>
</UserControl>
who belongs to the ViewModel AllCustomersViewModel:
public class AllCustomersViewModel : WorkspaceViewModel
{
(...)
public ObservableCollection<CustomerViewModel> AllCustomers { get; private set; }
(...)
}
but he uses a ResourceDictionary where he applies a DataTemplate between the View and the ViewModel:
<DataTemplate DataType="{x:Type vm:AllCustomersViewModel}">
<vw:AllCustomersView />
</DataTemplate>
but my problem is because i am not using a ResourceDictionary, and because of that i thought that i can put the DataTemplate in the Resources of the Window where i will have my View (for me is the more logic place to put the DataTemplate)… But for some reason the Data isn’t appearing in the ListView, and so i ask why?
I wouldn’t attach the view model in the Xaml. This hard-codes the Xaml to a specific view model.
Instead, I’d override the Application startup:
See this article:
http://www.codeproject.com/KB/WPF/MVVMQuickTutorial.aspx
This approach is also helpful if you use some sort of tool to dynamically bind your view models in the future, like MEF, Castle.Windsor or Prism.