【发布时间】:2011-01-06 18:38:17
【问题描述】:
我有一个DataTemplate 对应一个ListBox,我有几个控件绑定到一个项目。我还想绑定到LayoutRoot.DataContext 上的一个值。我不确定该怎么做。
<!--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;
}
}
这不起作用;仅显示 _data 项目。 Debug 输出中出现以下绑定错误:
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')..
我在某处有语法错误吗?
更新我的目标是这样的:
- 富
- 月亮
- 酒吧
- 月亮
- 巴兹
- 月亮
相反,我得到的只是:
- 富
- 酒吧
- 巴兹
(我正在为 Windows Phone 7 使用 Silverlight。)
【问题讨论】:
标签: c# silverlight xaml data-binding windows-phone-7