我有一个WPF窗口,其中设置了一个视图模型作为其DataContext,并且有一个ListBox,其中包含DataTemplate并且ItemsSource绑定到视图模型,如下例所示:
视图模型:
using System.Collections.Generic;
namespace Example
{
class Member
{
public string Name { get; set; }
public int Age { get; set; }
}
class Team
{
private List<Member> members = new List<Member>();
public string TeamName { get; set; }
public List<Member> Members { get { return members; } }
}
}
MainWindow.xaml:
<Window x:Class="Example.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:Example"
Title="Example" Height="300" Width="300" Name="Main">
<Window.DataContext>
<l:Team TeamName="The best team">
<l:Team.Members>
<l:Member Name="John Doe" Age="23"/>
<l:Member Name="Jane Smith" Age="20"/>
<l:Member Name="Max Steel" Age="24"/>
</l:Team.Members>
</l:Team>
</Window.DataContext>
<ListBox ItemsSource="{Binding Path=Members}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=TeamName}" Margin="4"/>
<TextBlock Text="{Binding Path=Name}" Margin="4"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
当然,团队类(Team class)的TeamName属性并未显示在ListBox项中,因为每个ListBox项都是List.ItemTemplate的DataContext,它会覆盖Window的DataContext。
问题是:我如何从ListBox的DataTemplate中对视图模型(Window.DataContext)的TeamName属性进行数据绑定?