I have several DataGrid
(actually an UserControl
based on a DataGrid
with filtering dialog, etc.) in a WPF project which show ObservableCollection<VisualXModel>
entities where VisualXModel
inherits from XModel
where X
stands for Field
, Item
, etc.
The XModel
are in a separate non-UI related library which includes the data access layer. Most of the properties in the XModel
are virtual and overriden in the VisualXModel
in order to deal with validation.
I also implemented the INotifyPropertyChanged
and INotifyDataErrorInfo
interfaces, but realise to lead to much duplicated codes.
I wonder if it shouldn't be possible to use a base class VisualModel<XModel>
which implements the interfaces as well as other common commands such as CopyCellCommand
, EditCommand
, RemoveCommand
.
But is there a way I can access the generic instance (type parameter) in the "overriden" properties which previously corresponded to the base class? The root part of the inheritance still remain the type parameter.
public class XModel
{
public int Id { get; set; }
public virtual string Name { get; set; } // Name is made editable from the UI.
}
Currently :
public class VisualXModel : XModel, INotifyPropertyChanged, INotifyDataErrorInfo
{
public override string Name
{
get => base.Name;
set
{
base.Name = value;
// Validation
// ..
OnPropertyChange(nameof(Name));
}
}
// Miscellaneous commands, such as Copy-to-clipboard
// ..
// INotifyPropertyChanged, INotifyDataErrorInfo implementations.. which is quite long to duplicate
// ..
}
With some refactoring
public class VisualModel<T> : INotifyPropertyChanged, INotifyDataErrorInfo
{
// Miscellaneous commands, such as Copy-to-clipboard
// ..
// INotifyPropertyChanged, INotifyDataErrorInfo implementations
// ..
}
public class VisualXModel : VisualModel<XModel>
{
public override string Name
{
get => How to access / get the Name property of the XModel instance?
set
{
How to access / set the Name property of the XModel instance?
// Validation
// ..
OnPropertyChange(nameof(Name));
}
}
}
VisualModel<XModel>
does not in any way define "instance of XModel"... If you thinkGeneric<T>
somehow creating instance ofT
you need to reread about generics.