WPF Simple Binding to INotifyPropertyChanged Object -


i've created simplest binding. textbox bound object in code behind.

event though - textbox remains empty.

the window's datacontext set, , binding path present.

can what's wrong?

xaml

<window x:class="anecdotes.simplebinding"         x:name="mainwindow"         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"         title="simplebinding" height="300" width="300" datacontext="mainwindow">     <grid>         <textbox text="{binding path=bookname, elementname=thebook}" />     </grid> </window> 

code behind

   public partial class simplebinding : window     {         public book thebook;          public simplebinding()         {             thebook = new book() { bookname = "the mythical man month" };             initializecomponent();         }     } 

the book object

public class book : inotifypropertychanged {     public event propertychangedeventhandler propertychanged;      protected void onpropertychanged(string name)     {         if (propertychanged != null)         {             propertychanged(this, new propertychangedeventargs(name));         }      }      private string bookname;      public string bookname     {         { return bookname; }         set         {             if (bookname != value)             {                 bookname = value;                 onpropertychanged("bookname");             }         }     } } 

first of remove datacontext="mainwindow" sets datacontext of window string mainwindow, specify elementname binding defines binding source control x:name="thebook" not exist in window. can make code work removing elementname=thebook binding , either assigning datacontext, default source if none specified, of window thebook

public simplebinding() {     ...     this.datacontext = thebook; }  

or specifying relativesource of binding window exposes thebook:

<textbox text="{binding relativesource={relativesource ancestortype={x:type window}}, path=thebook.bookname}"/> 

but since cannot bind fields need convert thebook property:

public partial class simplebinding : window {     public book thebook { get; set; }     ... } 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -