WPF DataGrid How to add blank row when binding to interface
I am trying to set up a DataGrid to have an empty row at the end using CanUserAddRows="True"
The same can be answered in several other questions like WPat datagrid allows user to add rows? and WPF DataGrid: empty row missing
One of the key points mentioned in the answers to both of these questions was
Make sure your objects in the ObeservableCollection have a default dimensionless constructor.
But I have a problem. The collection I'm linking is defined like this:
public ObservableCollection<IDataItem> ItemList { get; }
So of course I cannot define a parameterless constructor as I am binding to an interface. So how can I do this?
I know that if binding to a set of specific objects then it all works.
And FWIW I am trying to use IOC (first time) through UnityContainer
, so any answers that work through Resolve<IDataItem>()
are appreciated.
Final code
I took Johan's answer and rolled around in my IOC container ideas by making a singleton factory for the UnityContainer. This resulted in code that looks like (using Johan's code)
void RegisterTypes()
{
IUnityContainer container = UnityFactory.Instance.Container;
container.RegisterType<IDataItem, DataItem >(new InjectionConstructor());
}
..
private readonly BindingList<IDataItem> _itemList = new BindingList<IDataItem>();
public ViewModel()
{
_itemList.AllowNew = true;
IUnityContainer container = UnityFactory.Instance.Container;
_itemList.AddingNew += (sender, e) => { e.NewObject = container.Resolve<IDataItem>(); };
}
public BindingList<IDataItem> ItemList
{
get { return _itemList; }
}
source to share
This answer has what you want ie:
private readonly BindingList<IDataItem> _itemList = new BindingList<IDataItem>();
public ViewModel()
{
_itemList.AllowNew = true;
_itemList.AddingNew += (sender, e) => e.NewObject = new DataItem(...);
// I don't think you want to show your IoC here
}
public BindingList<IDataItem> ItemList
{
get { return _itemList; }
}
source to share