我正在使用 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/