Nick Hodges
Nick Hodges

Reputation: 17138

In MVVM, should the View know about the model?

A simple point of clarification. I believe the answer is "no", but I want to be sure.

Is it proper for the View to have knowledge of the Model?

As I said, I think the answer should be "no", but I'm finding it hard to design a simple MVVM demo without having the view know about the model.

Upvotes: 3

Views: 2002

Answers (2)

zzfima
zzfima

Reputation: 1565

Sometimes View should know the Model. When i use DataTemplate.

<UserControl x:Class="WpfApp2.MyView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<StackPanel>
    <ListBox ItemsSource="{Binding Persons}" BorderBrush="Transparent" x:Name="mainListBox"
     Grid.IsSharedSizeScope="True"
     HorizontalContentAlignment="Stretch">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Margin="4">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" SharedSizeGroup="Key" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="{Binding Name}" FontWeight="Bold"/>
                    <TextBox Text="{Binding Age}" Grid.Column="1"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

    <TextBox Text="{Binding ElementName = mainListBox, Path = SelectedItem.Age}"></TextBox>
</StackPanel>

As you seen, View knows my Model becouse of Name and Age

Upvotes: 0

XaviMuste
XaviMuste

Reputation: 304

You're right.Answer is NO.

[ The View binds to properties on a ViewModel, which, in turn, exposes data contained in Model objects and other state specific to the view. The bindings between view and ViewModel are simple to construct because a ViewModel object is set as the DataContext of a view. If property values in the ViewModel change, those new values automatically propagate to the view via data binding. For example, when the user clicks a button in the View, a command on the ViewModel executes to perform the requested action. The ViewModel, never the View, performs all modifications made to the model data. ] There's this useful link where you can have examples abouot this explanation: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Upvotes: 2

Related Questions