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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With