MVVM 嵌套列表滚动



我目前正在开发一个数据驱动的编辑工具,该工具是使用 MVVM 用 WPF 编写的。主显示是视图模型的可滚动列表,其中一些(不是全部)具有自己的子视图模型的内部列表(不可滚动)。问题在于,视图模型类型之一是数组类型,其中包含添加新子项的功能,我们希望这样做,以便如果您使用它,它将整个列表滚动到该新项。有没有使用 MVVM 的合理方法?

为了让您了解此 UI 当前是如何设置的,以下是整体显示:

<Grid ScrollViewer.VerticalScrollBarVisibility="Auto">
  <Label Content="{Binding Path=DisplayName}" Height="28" HorizontalAlignment="Left" Margin="4,4,0,0" VerticalAlignment="Top" />
  <ItemsControl IsTabStop="False" ItemsSource="{Binding Path=VMEntries}" Margin="12,25,12,12" ItemTemplateSelector="{StaticResource EntryTemplateSelector}" ScrollViewer.VerticalScrollBarVisibility="Auto">
    <ItemsControl.Template>
      <ControlTemplate>
        <ScrollViewer x:Name="ScrollViewer">
          <ItemsPresenter />
        </ScrollViewer>
      </ControlTemplate>
    </ItemsControl.Template>
  </ItemsControl>
</Grid>

这是我们正在处理的数组条目的数据模板:

<DataTemplate x:Key="Array">
  <Grid Margin="2,7,0,0">
    <Label Content="{Binding Path=DisplayName}" ToolTip="{Binding Path=Tooltip}"/>
    <Button Content="Add" HorizontalAlignment="Right" VerticalAlignment="Top"  Height="24" Width="24" Command="{Binding Path=AddCommand}"/>
    <ItemsControl HorizontalAlignment="Stretch" IsTabStop="False" ItemsSource="{Binding Path=SubEntries, NotifyOnSourceUpdated=True}" Margin="10,24,0,0" >
      <ItemsControl.ItemTemplate>
        <DataTemplate>
          <Grid HorizontalAlignment="Stretch">
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="Auto" />
              <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Button Name="RemoveButton" Grid.Column="0" Margin="0,5,0,0" Content="Del" HorizontalAlignment="Right" VerticalAlignment="Top"  Height="24" Width="24" Command="{Binding Path=RemoveCommand}" CommandParameter="{Binding Path=.}"/>
            <ContentControl Grid.Column="1" Content="{Binding Path=.}"  ContentTemplateSelector="{StaticResource EntryTemplateSelector}" />
          </Grid>
          <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding Path=RemoveHandler}" Value="{x:Null}">
              <Setter Property="Visibility" TargetName="RemoveButton" Value="Collapsed"/>
            </DataTrigger>
          </DataTemplate.Triggers>
        </DataTemplate>
      </ItemsControl.ItemTemplate>
    </ItemsControl>
  </Grid>
</DataTemplate>

MVVM 的理想不是在后面添加代码,但对于一些复杂的事情,更简单的方法是添加它。在某些情况下,如果要在应用程序上添加复杂的行为并保留 MVVM,另一种方法是使用行为(允许使用并从 XAML 绑定的 c# 代码)。还可以使用 AttachedProperties 定义行为,并注册到 PropertyChanged 事件。另一种选择是创建一个用户控件并将后面的代码添加到其中。

在您的特定情况下,内部集合在向其添加项时必须引发某个事件,然后在外部集合中执行类似 list.ScrollIntoView(itemToScroll); 。希望这可以提供一些提示。

最新更新