我正在使用 MVVM。我使用一些代码将数据网格绑定到集合:
<commonMVVMControls:GridControl DataContext="{Binding Path=ClientsListGrid,
Mode=TwoWay}"
它是 DataGridControl 类:
public class GridControl : DataGrid
{
public GridControl()
{
this.DataContextChanged += new System.Windows.DependencyPropertyChangedEventHandler(GridControl_DataContextChanged);
}
void GridControl_DataContextChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
{
var bindingItemsSource = new Binding("ItemsSource");
bindingItemsSource.Source = this.DataContext;
this.SetBinding(DataGrid.ItemsSourceProperty, bindingItemsSource);
this.RowStyle = new Style(typeof(DataGridRow));
this.RowStyle.Setters.Add(new Setter(DataGridRow.IsSelectedProperty, new Binding("IsSelected")));
}
现在是 ViewModel 中的一段代码:
var selectedClient = this.ClientsListGrid.ItemsSource.Where(x => x.IsSelected);
if (!selectedClient.Any())
{
MessageBox.Show(Resource.Resource.UpdateUserError, Resource.Resource.Warning, MessageBoxButton.OK, MessageBoxImage.Stop,
MessageBoxResult.OK);
return;
}
var viewModel = new AddOrUpdateClientViewModel(_serviceContext, selectedClient.First());
它运作良好。但是,如果我向下或向上滚动数据网格,它就会停止工作,并且 IsSelected 总是等于 false。