ScrollViewer中的ListView:所选项目不可见

时间:2015-03-15 21:23:52

标签: wpf

我在ScrollViewer中有一个ListView。我的期望是所选项目始终可见,这意味着ScrollViewer可以将其显示出来。然而,这不会发生。我错过了什么?

这是XAML:

<Window x:Class="tt.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:local="clr-namespace:tt"
    Title="MainWindow" Height="250" Width="200">

<Grid>
    <ScrollViewer>
        <ListView ItemsSource="{Binding MyData}" VerticalAlignment="Stretch" VerticalContentAlignment="Stretch"
                  IsSynchronizedWithCurrentItem="True">
            <ListView.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ListView.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid Margin="5" Background="AliceBlue">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>
                        <Button>xx</Button>
                        <TextBlock Grid.Row="1" Text="{Binding}" Margin="20"/>
                        <TextBlock Grid.Row="2" Text="{Binding}" Margin="20"/>
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ListView>
    </ScrollViewer>
</Grid>
</Window>

这是代码(将第11个元素设置为选定项目):

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public ObservableCollection<String> MyData { get; set; }
    ICollectionView dedaultView;

    public MainWindow()
    {
        InitializeComponent();
        MyData = new ObservableCollection<string>() {
            "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve"
        };
        dedaultView = CollectionViewSource.GetDefaultView(MyData);
        dedaultView.MoveCurrentToPosition(10);
        DataContext = this;
     }
}

1 个答案:

答案 0 :(得分:1)

您只需以这种方式扩展ListView控件:

public class ListView : System.Windows.Controls.ListView
{
    protected override void OnSelectionChanged(SelectionChangedEventArgs e)
    {
        base.OnSelectionChanged(e);

        ScrollIntoView(SelectedItem);
    }
}

然后在您的XAML中使用它。 我希望它可以帮到你。