MVVM.在某些情况下,为View添加代码是否合理?

Nov*_*zky 7 wpf binding mvvm

我有一个View,它有一个绑定到我的ViewModel(MVVM模式)的项目列表.

让我们说它看起来像那样:

<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>
Run Code Online (Sandbox Code Playgroud)

当用户向MessageLog添加内容(VM中有一个属性MessageLog)时,我想自动滚动到最新的项目.

换句话说,我只想在用户键入消息并点击输入时自动移动滚动条(就像Skype一样).

MessageLog上的绑定按预期工作,并在视图上更新项目.(我很高兴,我想这样离开)

我想知道如果使用MVVM模式方法,我仍然可以在View后面的代码文件中实现自动滚动吗?这似乎是相当逻辑的,因为滚动行为与VM无关,而ViewModel对View没有任何了解.这样对吗?我是正确的方式还是我错过了什么?

一般来说,在向View添加实现时有意义吗?

Ree*_*sey 9

是的,这是完全可以接受的.由于此处的逻辑与100%View相关,因此将其添加到View中没有问题.

MVVM是关于将您的应用程序逻辑与View逻辑分离,而不一定是从您的View中剥离100%的代码.

话虽这么说,但有替代方法可以解决这个问题.附加属性(或行为)对于像这样的任务来说是一个很好的选择 - 它们具有在以后的其他视图中可重用的大优势,因此如果您决定在用户​​的其他部分中想要相同的行为,则不要再重新发布它接口.

  • @pete:我写了一篇描述使用行为的文章:http://reedcopsey.com/2009/10/09/using-behaviors-to-allow-the-viewmodel-to-manage-view-lifetime-in-mv- VM / (2认同)
  • @pete:Nishant Sivakumar也将它移植到标准附属道具上.请参阅:http://reedcopsey.com/2010/04/15/attached-property-port-of-my-window-close-behavior/ (2认同)