我想以编程方式将一行数据网格放入视图中.我有超过100行.当我创建一个行(我正在通过向一个可观察的集合中添加一个项目来做)时,我希望选择该新行并将其带入视图.我能够在我的代码中选择新行但无法进行滚动.更多我希望该行的第一个单元格处于编辑模式,以便用户可以输入文本.我正在关注应用程序的MVVM模式,并希望在我的视图中保留零代码.我怎样才能做到这一点?
任何帮助或建议将不胜感激....
更新:
这就是我在XAML中所做的
<telerik:RadGridView ItemsSource="{Binding AllPartClasses}"
SelectedItem="{Binding SelectedPartClassViewModel, Mode=TwoWay}"
SelectionMode="Single" IsSynchronizedWithCurrentItem="True">
Run Code Online (Sandbox Code Playgroud)
在我的视图模型中,我做到了这一点
void AddNewPartClassExecute()
{
PartClass newPartClass = new PartClass();
PartClassViewModel tempPartClass = new PartClassViewModel(newPartClass);
tempPartClass.IsInValid = true;
AllPartClasses.Add(tempPartClass);
SelectedPartClassViewModel = tempPartClass;
Global.DbContext.PartClasses.AddObject(newPartClass);
//OnPropertyChanged("AllPartClasses");
}
public PartClassViewModel SelectedPartClassViewModel
{
get
{
return _selectedPartClassViewModel;
}
set
{
_selectedPartClassViewModel = value;
OnPropertyChanged("SelectedPartClassViewModel");
}
}
Run Code Online (Sandbox Code Playgroud)
它对我不起作用.
对于常规WPF,DataGrid您可以使用ScrollIntoView.在您的视图中,将SelectionChanged事件连接到视图代码隐藏cs文件中的以下内容.
private void OnSelectionChanged( object sender, SelectionChangedEventArgs e )
{
Selector selector = sender as Selector;
DataGrid dataGrid = selector as DataGrid;
if ( dataGrid != null && selector.SelectedItem != null && dataGrid.SelectedIndex >= 0 )
{
dataGrid.ScrollIntoView( selector.SelectedItem );
}
}
Run Code Online (Sandbox Code Playgroud)
当遵循 MVVM 模式时,您不应该执行特定于 UI 的操作,例如从代码中滚动。
解决方案很简单 - 只需将DataGrid.SelectedItem绑定到 ViewModel 中的属性,并且在项目集合中添加新项目时,只需更新绑定到的属性,SelectedItem以便它将引用刚刚添加的项目,并且数据网格应自动选择适当的行。
<DataGrid
ItemsSource="{Binding UnderyingItemsCollection}"
SelectedItem="{Binding RecentlyAddedItem, Mode=TwoWay}"
IsSynchronizedWithCurrentItem="True">
Run Code Online (Sandbox Code Playgroud)