wpf - C#: Cast to Base -
i have datagrid column contains link. file gets opened on click
<datagridhyperlinkcolumn binding="{binding path=number}" > <datagridhyperlinkcolumn.elementstyle> <style> <eventsetter event="hyperlink.click" handler="linkclicked"/> </style> </datagridhyperlinkcolumn.elementstyle> </datagridhyperlinkcolumn>
i use method
public void linkclicked(object sender, routedeventargs e) { var vm = (basepartviewmodel<part>) datacontext; vm.openfile(); }
i use code in base viewmodel class.
but problem cast not work
(basepartviewmodel<part>) datacontext
because every implementation different. instance
(basepartviewmodel<plug>) datacontext
and plug
derives part
. how make work without implementing method in every derived viewmodel?
you factor out openfile method covariant interface , cast interface.
interface myinterface<out t> { void openfile(); } class plug : part { } class part { } class basepartviewmodel<t> : myinterface<t> { public void openfile() { throw new notimplementedexception(); } } class program { static void main(string[] args) { basepartviewmodel<plug> derived = new basepartviewmodel<plug>(); myinterface<part> b = derived; b.openfile(); } }
Comments
Post a Comment