Binding to properties on the Window
I just got a question from someone who wanted to bind to properties on his Window class in his code behind and assumed that by simply saying <Binding Path="MyProperty"/> the Binding will automatically refer to the Window class. It is important to note that by default the Binding bind to properties on the DataContext of that element and not to those of the Window file.
So the right way to bind to properties on the Window is
<Window x:Class="demo.Window1"
xmlns=https://schemas.microsoft.com/winfx/avalon/2005
xmlns:x=https://schemas.microsoft.com/winfx/xaml/2005
Title="demo"
x:Name="window" >
<Grid x:Name="myGrid">
<TextBlock Text="{Binding ElementName=window, Path=SimpleProperty}"/>
</Grid>
</Window>
or by setting the DataContext to the Window.
<Window x:Class="demo.Window1"
xmlns=https://schemas.microsoft.com/winfx/avalon/2005
xmlns:x=https://schemas.microsoft.com/winfx/xaml/2005
Title="demo"
x:Name="window" >
<Grid x:Name="myGrid" DataContext="{Binding ElementName=window}" >
<TextBlock Text="{Binding Path=SimpleProperty}"/>
</Grid>
</Window>
Infact, ElementName property on Binding lets you refer to any element in the current namescope and bind to properties on it. Now let me explain namescope since i've introduced it. A NameScope defines a scope in which you can only have one element with a specific unique name, and from which you can Find any element via name uniquely. A Page is one such scope, a Template and a Style is another scope. So from within a Template you can only refer to elements in that Template, similarly from within a Page you can only refer to elements in that page.
- Namita
Comments
- Anonymous
June 15, 2009
PingBack from http://mydebtconsolidator.info/story.php?id=18254