c# - wpf mvvm 中的 Datagrid SelectedIndex 在 RaisePropertyChanged 上设置为 0

标签 c# wpf xaml mvvm datagrid

我正在使用 mvvm light 在 c# Wpf 中开发一个项目。

在这个项目中,我有一个数据网格,其中 SelectedIndex 绑定(bind)到 ViewModel 中的一个 int。

文档 View 模型:

private int _docSelectedIndex;
    public int DocSelectedIndex
    {
        get { return _docSelectedIndex; }
        set
        {

            _docSelectedIndex = value;
            RaisePropertyChanged("DocSelectedIndex");

        }
    }

View :

<DataGrid HeadersVisibility="Column"
                  x:Name="docgrid" 
                  IsSynchronizedWithCurrentItem="True"
                  DataContext ="{Binding Document, Source={StaticResource Locator}}"
                  ItemsSource="{Binding Path=DocItems}"
                  SelectedIndex="{Binding DocSelectedIndex,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
             ...
             ...
</DataGrid>

绑定(bind)有效!但是每当我想用新数据更新网格时,我需要 RaisePropertyChanged("DocItems")。

这似乎将 selectedindex 更改为 0。我尝试将 selectedindex 设置回原来的位置,但索引最终始终设置为 0。

这是调用 RaisePropertyChanged 的​​方法:

public void UpdateDocumentList(object sender, TypedEventArg<DocListUpdatedEvent> e) 
    {
        var temp = new List<SFODocument>(e.Value.DocumentList);
        var meta = _meta.GetPageMetaData();

        foreach (var d in temp)
        {
            foreach (int i in d.PageList) 
            {
                meta[i].docid = d.DocumentID;
                _meta.UpdateExistingMeta(meta[i]);
            }

        }
        _docItems = new ObservableCollection<SFODocument>(temp);
        RaisePropertyChanged("DocItems");
    }

如何更新数据网格并仍然保留原始的 selectedIndex ?

最佳答案

尝试通过这种方式将selectedindex设置回原来的状态

Dispatcher.BeginInvoke(new Action(() => docgrid.SelectedIndex = oldIndex), DispatcherPriority.DataBind);

如果它不起作用,请尝试使用其他优先级。

关于c# - wpf mvvm 中的 Datagrid SelectedIndex 在 RaisePropertyChanged 上设置为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22373509/

相关文章:

c# - 如何在 C# 中的 Dispose() 方法中处理托管资源?

c# - 在 map 上作为图钉的图像 - Windows Phone 8

c# - 简单的 WPF 示例会导致内存增长失控

c# - WPF:组合框在绑定(bind) ItemSsource 集合更改后丢失 selectedindex

c# - ContentView 中的 BindableProperty 不起作用

c# - 如何在Silverlight 5控件中显示HTML内容

WPF:如何以编程方式设置 ListView 的样式,以便所有行都具有特定的背景颜色和高度?

c# - 将图像加载到 wp7 中的应用程序栏

c# - 绑定(bind) DataGrid 中的 ComboBox header

c# - WPF MVVM 绑定(bind)超链接 RequestNavigate 到 View 模型