Hi I have a WPF datagrid which is bound with TrulyObservableCollection, Whenever I try editing a cell through textinput the datagrid cell looses focus after each key entered,
public sealed class TrulyObservableCollection<T> : ObservableCollection<T>
where T : INotifyPropertyChanged
{
public TrulyObservableCollection()
{
CollectionChanged += FullObservableCollectionCollectionChanged;
}
public TrulyObservableCollection(IEnumerable<T> pItems)
: this()
{
foreach (var item in pItems) {
this.Add(item);
}
}
private void FullObservableCollectionCollectionChanged(object sender,
NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null) {
foreach (Object item in e.NewItems) {
((INotifyPropertyChanged)item).PropertyChanged += ItemPropertyChanged;
}
}
if (e.OldItems != null) {
foreach (Object item in e.OldItems) {
((INotifyPropertyChanged)item).PropertyChanged -= ItemPropertyChanged;
}
}
}
private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
try {
var a = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
OnCollectionChanged(a);
}
catch {
// ignored
}
}
}
Below is my ViewModel, Which is binded to Datagrid,
public TrulyObservableCollection<SubLotModel> SubLotCollection
{
get { return _subLotCollection; }
set
{
_subLotCollection = value;
NotifyOfPropertyChange(() => SubLotCollection);
SerialNumberAdded = _subLotCollection.Count;
}
}
In the Datagrid i have a textbox column which is binded to Quantity property in SublotCollection,
<DataGridTemplateColumn Header="Quantity">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Quantity, ValidatesOnDataErrors=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
As soon as i type a valid key in texbox column the cell loses focus.
Quantityproperty is updated raising thePropertyChangedevent, which causes yourTrulyObservableCollectionto raiseCollectionChangedwithNotifyCollectionChangedAction.Reset, which in turn causes theDataGridto rebuild itself, causing previously focused editor to lose the focus (possibly it's not even the same editor anymore, but a newly created instance in it's place). - Grx70