选择任何项目后,列表框焦点重置

时间:2017-11-17 18:59:16

标签: c# wpf xaml listbox focus

我的WPF项目中有一个由MYSql数据库填充的列表框。当我在列表框中的任何位置滚动并选择一个项目时,它会立即跳转到第一个项目并从头开始显示列表。我试过this solution,但它给了我NullException。这是代码:

private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var addedItems = e.AddedItems;
    var selectedItem = (object)null;
    if (addedItems.Count > 0)
    {
        selectedItem = addedItems[0];
    }

    object id = (((System.Data.DataRowView)selectedItem).Row.ItemArray[0]);
    object name = (((System.Data.DataRowView)selectedItem).Row.ItemArray[1]);
    object selectedType = (((System.Data.DataRowView)selectedItem).Row.ItemArray[2]);
}

和xaml部分:

<ScrollViewer Width="582.5" Name="scrollViewer"  HorizontalAlignment="Center" Background="Transparent" VerticalAlignment="Bottom"  VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Hidden" >
    <ListBox x:Name="listBox" SelectionMode="Single"   Visibility="Hidden" IsEnabled="False" ScrollViewer.VerticalScrollBarVisibility="Disabled" ScrollViewer.HorizontalScrollBarVisibility="Disabled"  HorizontalAlignment="Center" Background="Transparent" BorderBrush="Transparent" SelectionChanged="listBox_SelectionChanged"  ItemsSource="{Binding Source={StaticResource TypeTable}}" HorizontalContentAlignment="Center" RenderTransformOrigin="0.5,0.5" Padding="0,0,0,90"  >
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Name="stackPanel2" CanHorizontallyScroll="True" Orientation="Horizontal" HorizontalAlignment="Right" Height="180" Width="180" >
                    <Image Margin="3" Source="{Binding pic_path}" RenderOptions.BitmapScalingMode="Fant" RenderOptions.EdgeMode="Aliased"/>
                    <TextBox Margin="3" Text="{Binding name}" Visibility="Visible"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</ScrollViewer>

0 个答案:

没有答案