C# MVVM嵌套列表滚动
我目前正在开发一个数据驱动的编辑工具,它是使用MVVM在WPF中编写的。主显示是视图模型的可滚动列表,其中一些(不是全部)具有其自己的子视图模型的内部列表(不可滚动)。问题在于,其中一种视图模型类型是一种数组类型,它包含添加新子项的功能,我们希望这样做,如果您使用它,它会将整个列表滚动到该新项。使用MVVM有没有一种合理的方法来实现这一点 为了让您了解当前如何设置此UI,以下是总体显示:C# MVVM嵌套列表滚动,c#,wpf,list,mvvm,C#,Wpf,List,Mvvm,我目前正在开发一个数据驱动的编辑工具,它是使用MVVM在WPF中编写的。主显示是视图模型的可滚动列表,其中一些(不是全部)具有其自己的子视图模型的内部列表(不可滚动)。问题在于,其中一种视图模型类型是一种数组类型,它包含添加新子项的功能,我们希望这样做,如果您使用它,它会将整个列表滚动到该新项。使用MVVM有没有一种合理的方法来实现这一点 为了让您了解当前如何设置此UI,以下是总体显示: <Grid ScrollViewer.VerticalScrollBarVisibility="Aut
<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事件。另一种方法是创建一个UserControl并将代码添加到其中
在您的特定情况下,向内部集合添加项时,内部集合必须引发一些事件,然后在外部集合中执行类似以下内容的操作list.ScrollIntoView(itemToScroll)代码>。希望这能给你一些建议