Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM. Is adding code to View justified in some cases?

Tags:

mvvm

binding

wpf

I have a View which has a list of items bound to my ViewModel (MVVM pattern).

Let's say it looks like that:

<ScrollViewer Width="Auto" Height="Auto">
    <ItemsControl ItemsSource="{Binding Path=MessageLog}" 
                  Grid.IsSharedSizeScope="True"                     
                  ScrollViewer.CanContentScroll="True">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="150" SharedSizeGroup="FullName"/>
                        <ColumnDefinition Width="*" SharedSizeGroup="MessageLog"/>
                    </Grid.ColumnDefinitions>                                   
                    <StackPanel>
                        <TextBlock Text="{Binding Path=PostedBy.FullName}" />
                        <TextBlock Text="{Binding Path=DatePosted}" />
                    </StackPanel>
                    <TextBlock Grid.Column="1" Text="{Binding Path=MessageLog}"/>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</ScrollViewer>

When user adds something to MessageLog (there is a property MessageLog in VM) I want to automatically scroll to the most recent item.

In other words, I just want to move the scrollbar automatically when user type a message and hit the enter (something like Skype does).

Binding on MessageLog works as expected and item is updated on the view. (I'm happy about that and I want to leave it like that)

I am wondering if using MVVM pattern approach, can I still implement an auto scroll in code behind file of the View? It seems to be quite logic as scrolling behavior has nothing to do with the VM and ViewModel doesn't know anything about the View. Is it right? Am I going right way or I am missing something?

Generally speaking, when adding an implementation to a View makes sense?

like image 888
Novitzky Avatar asked Oct 25 '10 16:10

Novitzky


1 Answers

Yes, this is perfectly acceptable. Since the logic here is 100% View related, there is no problem with adding it to the View.

MVVM is about separating your Application logic from your View logic, not necessarily about stripping 100% of the code out of your View.

That being said, there are alternatives to code behind for this. Attached properties (or Behaviors) are a great option for tasks like these - they have the large advantage of being reusable in other Views later, so you don't reinvent this later if you decide you want the same behavior in other parts of your User Interface.

like image 131
Reed Copsey Avatar answered Oct 05 '22 07:10

Reed Copsey