Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save marbel82/1bd29eaac22695427268a35566021802 to your computer and use it in GitHub Desktop.
Save marbel82/1bd29eaac22695427268a35566021802 to your computer and use it in GitHub Desktop.
Replacement of DataContextChanged handler defined locally for generic
public class CarViewModel
{
public ICarView View { get; set; }
}
//============================================================
// Before
public class CarView : UserControl, ICarView
{
public CarView()
{
InitializeComponent();
DataContextChanged += UserControl_DataContextChanged;
}
private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue is CarViewModel vm_old)
{
if (vm_old.View == this)
vm_old.View = null;
}
if (e.NewValue is CarViewModel vm_new)
{
vm_new.View = this;
}
}
}
//============================================================
// After
public class CarView : UserControl, ICarView
{
public CarView()
{
InitializeComponent();
DataContextChanged += CreateHandlerForAssigningVToVM<CarViewModel, ICarView>(m => m.View, (m, v) => m.View = v);
}
DependencyPropertyChangedEventHandler CreateHandlerForAssigningVToVM<VM, V>(Func<VM, V> vmViewGetter, Action<VM, V> vmViewSetter) where V : class
{
void DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue is VM vm_old)
{
if (ReferenceEquals(vmViewGetter(vm_old), sender))
vmViewSetter(vm_old, null);
}
if (e.NewValue is VM vm_new)
{
vmViewSetter(vm_new, (V)sender);
}
}
return new DependencyPropertyChangedEventHandler(DataContextChanged);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment