c# - Binding dependency property - set in custom user control, get in viewmodel -


the aim instantiate object in custom usercontrol , access instance viewmodel. following not working, upratings property in viewmodel null.

custom usercontrol dependency property

public partial class scale:usercontrol {      public scale()     {         initializecomponent();     }      public static readonly dependencyproperty mouseratingsproperty =          dependencyproperty.register(         "mouseratings",         typeof(iobservable<double>),         typeof(scale));      public iobservable<double> mouseratings     {                 {             return (iobservable<double>)getvalue(mouseratingsproperty);         }         set         {             setvalue(mouseratingsproperty, value);                         }     }      // requires system.reactive nuget     private isubject<double> _mouseratings = new subject<double>();      protected override void oninitialized(eventargs e)     {         base.oninitialized(e);         // _mouseratings object instance need access in viewmodel         mouseratings = _mouseratings;     } } 

view

<stackpanel>     <scale:scale mouseratings="{binding path=upratings, mode=twoway}"/> </stackpanel> 

viewmodel

// requires prism.wpf nuget public class myviewmodel : bindablebase {     public iobservable<double> upratings { get; set; }      // called after datacontext set, upratings binding should work here     // see https://github.com/prismlibrary/prism/blob/master/documentation/wpf/60-navigation.md     public void onnavigatedto(navigationcontext navigationcontext)     {         // upratings unfortunately null here         trace.writeline(upratings == null ? "null" : "not null");     }  } 

note datacontext not set directly on custom usercontrol parent of hers (and can confirm inside custom usercontrol).

it started work when mouseratings = _mouseratings; called later follows, while mouseratings lost value mysterious reason if setting oninitialized.

public scale()     {         initializecomponent();         isvisiblechanged += scale_isvisiblechanged;     }  private void scale_isvisiblechanged(object sender, dependencypropertychangedeventargs e)     {         if (isvisible)         {             mouseratings = _mouseratings;         }     } 

it work set in usercontrol loaded event, viewmodel has wait time before being able access object.


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -