If one were to compile and run the following code, one would find that selecting and/or deselecting a row causes a line to be written to the Output window (as closer inspection of said code would lead one to believe).
After a short time of changing the selected row of the grid using the arrow keys (holding the Up and Down arrows respectively to traverse the entire data set a few times), one would be shocked (as I was) to notice that Output messages cease, even while continuing to cycle through the grid's rows.
I am attempting to achieve something similar to what was given in this answer.
I am absolutely baffled. What would cause Bindings on my grid to spontaneously fail? Any and all help here would be MUCH appreciated!! Also, should anyone have the time to reproduce this, please comment with your findings.
XAML:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<DataGrid Name="TheGrid">
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="IsSelected"
Value="{Binding Mode=TwoWay, Path=IsSelected}"/>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True"
Binding="{Binding Name}" Header="Name"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
Code-behind:
using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;
namespace WpfApplication1 {
public partial class Window1 : Window {
public Window1() {
InitializeComponent();
TheGrid.ItemsSource = Enumerable.Range(1, 100)
.Select(i => new MyClass("Item " + i));
}
}
public class MyClass : INotifyPropertyChanged {
public string Name { get; private set; }
private bool m_IsSelected;
public bool IsSelected {
get {
return m_IsSelected;
}
set {
if (m_IsSelected != value) {
m_IsSelected = value;
Console.WriteLine(Name + ": " + m_IsSelected);
PropertyChanged(this,
new PropertyChangedEventArgs("IsSelected"));
}
}
}
public MyClass(string name) {
Name = name;
}
public event PropertyChangedEventHandler PropertyChanged =
delegate { };
}
}
Thanks in advance!
EDIT:
Tried applying the
DataGridRow
Style using the RowStyleSelector property - fail.Tried applying the
DataGridRow
Style using theRow_Loading
andRow_Unloading
events - fail.Tried using a custom MultiSelectCollectionView - fail (didn't work with DataGrid control)
Tried setting
VirtualizingStackPanel.IsVirtualizing="False"
- fail (unusably slow with hundreds of rows)Tried messing with
VirtualizingStackPanel.VirtualizationMode
(Standard or Recycled) - fail.
As stated in one of my comments below, the overarching problem is that I need to bind the SelectedItems property of the DataGrid to my ViewModel, but can't, since SelectedItems is read-only.
There HAS to be some kind of pure-MVVM, out-of-the-box solution for this, but so far, it eludes me!