Silverlight: Binding to a LayoutRoot value from within a DataTemplate
- by Rosarch
I have a DataTemplate for a ListBox, where I have several controls that bind to an item. I would also like to bind to a value on LayoutRoot.DataContext. I'm unsure of how to do this.
<!--LayoutRoot is the root grid where all page content is placed-->
<StackPanel x:Name="LayoutRoot" Background="Transparent">
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding}" />
<TextBlock Text="{Binding ElementName=LayoutRoot, Path=DataContext.Foo}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
public partial class MainPage : PhoneApplicationPage
{
public string Foo
{
get
{
return "the moon";
}
}
private int startIndex = 1;
private IList<string> _data = new List<string>() { "foo", "bar", "baz" };
public IList<string> Items
{
get
{
return _data;
}
}
// Constructor
public MainPage()
{
InitializeComponent();
LayoutRoot.DataContext = this;
}
}
This doesn't work; only the _data items are displayed. The following binding errors appear in the Debug output:
System.Windows.Data Error: BindingExpression path error: 'Foo' property not found on 'foo' 'System.String' (HashCode=1502598398). BindingExpression: Path='DataContext.Foo' DataItem='System.Windows.Controls.Border' (HashCode=78299055); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String')..
System.Windows.Data Error: BindingExpression path error: 'Foo' property not found on 'bar' 'System.String' (HashCode=696029481). BindingExpression: Path='DataContext.Foo' DataItem='System.Windows.Controls.Border' (HashCode=78298703); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String')..
System.Windows.Data Error: BindingExpression path error: 'Foo' property not found on 'baz' 'System.String' (HashCode=696029489). BindingExpression: Path='DataContext.Foo' DataItem='System.Windows.Controls.Border' (HashCode=78298694); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String')..
Do I have a syntax error somewhere?
Update I'm aiming for something that looks like this:
foo
the moon
bar
the moon
baz
the moon
Instead, all I'm getting is:
foo
bar
baz