wpf - Public Property Data Binding failing in Xaml -


my code behind file has corresponding view model public property 1 of windows. tried data bind viewmodel ui elements in xaml error messages that. however, when try create data bind using code, works without issues. confused why happening , guidance on doing wrong.

scenario 1 - data binding fails when done in xaml

productinfowindow.xaml:

<window ...>     <grid name="grdprod" datacontext="{binding relativesource={relativesource self}, path=viewmodel}">         <textbox name="txtname" text="{binding product.name}" />     </grid> </window> 

productinfowindow.xaml.cs:

public partial class productinfowindow : window {     public productinfoviewmodel viewmodel { get; set; }      public productinfo()     {         viewmodel = new productinfoviewmodel(...);     } } 

error messages in output window:

system.windows.data error: 40 : bindingexpression path error: 'viewmodel' property not  found on 'object' ''grid' (name='grdprod')'. bindingexpression:path=viewmodel;  dataitem='grid' (name='grdprod'); target element 'grid' (name='grdprod'); target  property 'datacontext' (type 'object') 

scenario 2 - data binding works when done in code

productinfowindow.xaml:

<window ...>     <grid name="grdprod">         <textbox name="txtname" text="{binding product.name}" />     </grid> </window> 

productinfowindow.xaml.cs:

public partial class productinfowindow : window {     public productinfoviewmodel viewmodel { get; set; }      public productinfo()     {         viewmodel = new productinfoviewmodel(...);         grdprod.datacontext = viewmodel;     } } 

edit (09/08/2013)

productinfoviewmodel.cs

public class productinfoviewmodel : inotifypropertychanged {     public event propertychangedeventhandler propertychanged;      public void onpropertychanged(propertychangedeventargs e)     {         if (propertychanged != null)             propertychanged(this, e);     }      private product m_product;      public product product     {                 {             return m_product;         }          set         {             m_product = value;             onpropertychanged(new propertychangedeventargs("product"));         }     }      public productinfoviewmodel(...)     {         product = new product(...);     } } 

your error message telling viewmodel property can't found on grid 'grdprod', fair point, because viewmodel public property defined on productinfowindow class.

try setting datacontext @ window level instead (adapting example):

<window datacontext="{binding relativesource={relativesource self}, path=viewmodel}" ...>     <grid name="grdprod">          <textbox name="txtname" text="{binding product.name}" />     </grid> </window> 

Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

jquery - How would i go about shortening this code? And to cancel the previous click on click of new section? -