OK… I’m a VB.NET WinForms guy trying to understand WPF and all of its awesomeness. I’m writing a basic app as a learning experience, and have been reading lots of information and watching tutorial videos, but I just can’t get off the ground with simple DataBinding, and I know I’m missing some basic concept. As much as I’d love it, I haven’t had that ‘Aha!’ moment when reviewing source code yet.
So… In my Window class I defined a custom string Property. When I go into Blend, I try to databind my TextBox’s Text to this property, but my Property doesn’t show up in Blend as something that available for Binding to.
Can someone tell me what I need to add to my code/XAML below… and most importantly why?
My XAML:
<Window x:Class='Window1' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' Title='Window1' Height='300' Width='300'> <Grid> <TextBox Text='How do I Bind my SomeText property here?'></TextBox> </Grid> </Window>
My Window Code:
Class Window1 Private _sometext As String = 'Hello World' Public Property SomeText() As String Get Return _sometext End Get Set(ByVal value As String) _sometext = value End Set End Property End Class
Here’s how you need to change your XAML (the code is fine).
To understand Bindings in WPF, you need to understand the DataContext. Every element has a DataContext property, and any object you put in that property becomes the data source of any bindings which do not have an explicit data source specified. The value of the DataContext is inherited from a parent object (so in this case the TextBox inherits the Grid’s DataContext, which inherits the Window’s DataContext). Since you want to refer to a property of the window, you need to set the DataContext to point to the Window instance, which is what I do in the DataContext attribute of the Window.
You can also change the data source for individual bindings by using the Source= or RelativeSource= syntax in the {Binding } element.