WPF:如果直接设置DataContext,则只能绑定到List



我正在学习WPF。提前感谢您的帮助。

我有一个对象Directory,它充当Person对象列表的容器。我不明白为什么我不能将ListBox绑定到Person列表,除非我直接设置DataContext。换句话说,我不能使用点表示法来访问列表作为目录的子属性。

观察下面C#sharp代码的最后一行:我将DataContext设置为this.directory.People,它工作得很好。

但是,如果我将DataContext简单地设置为this(指代整个窗口),然后尝试使用点表示法来设置像<ListBox ItemsSource="{Binding Path=directory.People}" />一样的绑定,则我的ListBox为空。

下面列出了XAML。观察XAML的最后一行。

CodeBehind:

public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Directory
{
public List<Person> People = new List<Person>();
public Directory()
{
this.People.Add(new Person() { Name = "Joseph", Age = 34 });
this.People.Add(new Person() { Name = "Teresa", Age = 29});
this.People.Add(new Person() { Name = "Kulwant", Age = 66 });
this.People.Add(new Person() { Name = "Hyunh", Age = 61});
this.People.Add(new Person() { Name = "Marcio", Age = 65 });
}
}

public partial class MainWindow : Window
{
public Directory directory { get; } = new Directory();
public MainWindow()
{
InitializeComponent();
this.DataContext = this.directory.People;
}
}

XAML:

<Window x:Class="WtfDataTrigger.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:t="clr-namespace:System.Threading;assembly=mscorlib"
xmlns:local="clr-namespace:LearningWPF"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type local:Person}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="1*" />
<RowDefinition Height="1*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label Name="NameLabel" Margin="2" Content="Name" Grid.Column="0" Grid.Row="0" VerticalAlignment="Center" FontWeight="Bold"/>
<TextBlock Name="NameText" Margin="2" Text="{Binding Path=Name}" Grid.Column="1" Grid.Row="0" VerticalAlignment="Center" />
<Label Name="AgeLabel" Margin="2" Content="Age" Grid.Column="0" Grid.Row="1" VerticalAlignment="Center" FontWeight="Bold" />
<TextBlock Name="AgeText" Margin="2" Text="{Binding Path=Age}" Grid.Column="1" Grid.Row="1" VerticalAlignment="Center"/>
</Grid>
</DataTemplate>
</Window.Resources>
<StackPanel>
<ListBox ItemsSource="{Binding}" />
</StackPanel>
</Window>

WPF数据绑定仅适用于公共属性。虽然directory是公共属性(但应命名为Directory),但People是公共字段。

更改

public List<Person> People = new List<Person>();

public List<Person> People { get; } = new List<Person>();

最新更新