【问题标题】:Silverlight: DataGrid.SelectedIndex always getting -1Silverlight:DataGrid.SelectedIndex 总是得到 -1
【发布时间】:2015-03-03 08:54:35
【问题描述】:

我的项目中有这个 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>

我将选定的行值保存在会话中:

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 并且第一行被选中。
有什么想法吗?

【问题讨论】:

    标签: c# silverlight datagrid


    【解决方案1】:

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

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

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

        ...
        INotifyCollectionChanged items = dataGrid.Items;
        items.CollectionChanged += OnItemsChanged;
        ...
    
    private void OnItemsChanged()
    {
        dataGrid.SelectedIndex = 42;
    }
    

    【讨论】:

    • 问题不在于初始化参数,如果我将dataGrid1.SelectedIndex 设置为例如2,它也会得到-1
    • @SirwanAfifi:听起来你设置索引太早了。请参阅我编辑的答案。
    猜你喜欢
    • 2022-11-16
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 2020-11-23
    相关资源
    最近更新 更多