Silverlight:DataGrid.SelectedIndex总是得-1

时间:2015-03-03 08:54:36

标签: c# silverlight datagrid

我的项目中有这个DataGrid:

<sdk:DataGrid  RowDetailsVisibilityChanged="dataGrid1_RowDetailsVisibilityChanged" Grid.Row="1"  Loaded="dataGrid1_Loaded" ItemsSource="{Binding ElementName=getVarede_ResultDomainDataSource, 
                          Path=Data}" RowDetailsVisibilityMode="Collapsed" AutoGenerateColumns="False" Style="{StaticResource DataGridStyle}" Height="Auto" IsReadOnly="True" 
                          HorizontalAlignment="Left" Name="dataGrid1" VerticalAlignment="Top" SelectionChanged="dataGrid1_SelectionChanged" 
                          MouseEnter="dataGrid1_MouseEnter" MouseLeave="dataGrid1_MouseLeave" GotFocus="dataGrid1_GotFocus" LoadingRow="dataGrid1_LoadingRow" 
                          KeyDown="dataGrid1_KeyDown" KeyUp="dataGrid1_KeyUp" LoadingRowDetails="dataGrid1_LoadingRowDetails" Cursor="Hand" Background="#FFCADCE8"  >
                //....


</sdk:DataGrid>

我将选定的行值保存在session:

之类的内容中
private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Application.Current.Host.InitParams["CurrentRow"] = dataGrid1.SelectedIndex.ToString();
    //...
}

因此,当DataGrid加载时,我想将存储值设置为SeletedIndex:

dataGrid1.SelectedIndex = int.Parse(Application.Current.Host.InitParams["CurrentRow"]);  

但它总是得-1,第一行被选中 有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您无法使用您发布的方法在会话之间保存Init参数。 这里是an article,描述了如何读取init参数并将它们存储在隔离存储中。 它们不应该像你在这里一样由你的代码设置:

Application.Current.Host.InitParams["CurrentRow"] = dataGrid1.SelectedIndex.ToString();

[编辑] 好的,在我读完你的最新评论之后......我明白了你的实际问题是什么。您过早地设置SelectedIndex方式。在Loaded事件处理程序中设置时,项目不存在。因此,您可以将索引设置为您想要的任何内容,只要控件中没有任何项目,它将始终回退到-1。你必须等到物品加载后才能设置所选的索引。 伪代码:

    ...
    INotifyCollectionChanged items = dataGrid.Items;
    items.CollectionChanged += OnItemsChanged;
    ...

private void OnItemsChanged()
{
    dataGrid.SelectedIndex = 42;
}