.net – 在WPF中,如何从包含ListBox的DataTemplate内部数据绑定到Window DataContext?

前端之家收集整理的这篇文章主要介绍了.net – 在WPF中,如何从包含ListBox的DataTemplate内部数据绑定到Window DataContext?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个 WPF窗口,其视图模型设置为其DataContext,并且具有一个带有DataTemplate的ListBox,其ItemsSource绑定到视图模型,如下例所示:

查看型号:

  1. using System.Collections.Generic;
  2.  
  3. namespace Example
  4. {
  5. class Member
  6. {
  7. public string Name { get; set; }
  8. public int Age { get; set; }
  9. }
  10.  
  11. class Team
  12. {
  13. private List<Member> members = new List<Member>();
  14.  
  15. public string TeamName { get; set; }
  16. public List<Member> Members { get { return members; } }
  17. }
  18. }

MainWindow.xaml:

  1. <Window x:Class="Example.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:l="clr-namespace:Example"
  5. Title="Example" Height="300" Width="300" Name="Main">
  6.  
  7. <Window.DataContext>
  8. <l:Team TeamName="The best team">
  9. <l:Team.Members>
  10. <l:Member Name="John Doe" Age="23"/>
  11. <l:Member Name="Jane Smith" Age="20"/>
  12. <l:Member Name="Max Steel" Age="24"/>
  13. </l:Team.Members>
  14. </l:Team>
  15. </Window.DataContext>
  16.  
  17. <ListBox ItemsSource="{Binding Path=Members}">
  18. <ListBox.ItemTemplate>
  19. <DataTemplate>
  20. <StackPanel Orientation="Horizontal">
  21. <TextBlock Text="{Binding Path=TeamName}" Margin="4"/>
  22. <TextBlock Text="{Binding Path=Name}" Margin="4"/>
  23. </StackPanel>
  24. </DataTemplate>
  25. </ListBox.ItemTemplate>
  26. </ListBox>
  27. </Window>

当然,TeamBox的TeamName属性不会显示在ListBox项中,因为LisBox的每个项都是List.ItemTemplate的DataContext,它会覆盖Window的DataContext.

问题是:如何从ListBox的DataTemplate中数据绑定到视图模型(Window.DataContext)的TeamName属性

我将l:Team声明提取到Window.Resources部分,并从DataContext和DataTemplate中引用它:
  1. <Window x:Class="Example.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:l="clr-namespace:Example"
  5. Title="Example" Height="300" Width="300" Name="Main">
  6.  
  7. <Window.Resources>
  8. <l:Team x:Key="data" TeamName="The best team">
  9. <l:Team.Members>
  10. <l:Member Name="John Doe" Age="23"/>
  11. <l:Member Name="Jane Smith" Age="20"/>
  12. <l:Member Name="Max Steel" Age="24"/>
  13. </l:Team.Members>
  14. </l:Team>
  15. <Window.Resources>
  16.  
  17. <Window.DataContext>
  18. <StaticResource ResourceKey="data"/>
  19. </Window.DataContext>
  20.  
  21. <ListBox ItemsSource="{Binding Path=Members}">
  22. <ListBox.ItemTemplate>
  23. <DataTemplate>
  24. <StackPanel Orientation="Horizontal">
  25. <TextBlock Text="{Binding Source={StaticResource data},Path=TeamName}" Margin="4"/>
  26. <TextBlock Text="{Binding Path=Name}" Margin="4"/>
  27. </StackPanel>
  28. </DataTemplate>
  29. </ListBox.ItemTemplate>
  30. </ListBox>
  31. </Window>

猜你在找的Windows相关文章