C# WPF 绑定到数据源的控件无法更新(显示空白)的解决办法

首先回顾一下在 WPF 中将控件进行数据绑定的写法。
例如,要将一个两列的 ListBox 进行数据绑定,在 XAML 中,该 ListBox 的 XAML 代码大致为

<ListBox Name="EmployeeList" HorizontalContentAlignment="Stretch">
	<ListBox.ItemTemplate>
		<DataTemplate>
			<Grid>
				<Grid.ColumnDefinitions>
					<ColumnDefinition Width="*"/>
					<ColumnDefinition Width="*"/>
				</Grid.ColumnDefinitions>
				<TextBlock Text="{Binding ID}" Grid.Column="0"/>
				<TextBlock Text="{Binding Name}" Grid.Column="1"/>
			</Grid>
		</DataTemplate>
	</ListBox.ItemTemplate>
</ListBox>

对应同名的 .cs 文件中的 C# 代码

class EmployeeListItem {
    
    
	public string ID {
    
     get; set; }
	public string Name {
    
     get; set; }
	
	public EmployeeListItem(string id, string name) {
    
    
		ID = id; Name = name;
	}
}
List<EmployeeListItem> Employees = new();
EmployeeList.ItemsSource = Employees;

需要注意:
数据源的每一项参与绑定的成员必须为属性,具有 get 和 set 两个 accessor,且必须为公有成员(public 修饰)。如果访问修饰符为 private,则无法在控件中显示数据。
例如,ListBox 控件 EmployeeList 绑定到了线性表 Employees,它由若干个 EmployeeListItem 构成,每个 EmployeeListItem 拥有两个成员 ID 和 Name,它们都必须为属性,且为 public。如果用 private 修饰这两个属性,那么在 EmployeeList 这个列表框中,就不能看到数据源 Employees 的内容。

Guess you like

Origin blog.csdn.net/COFACTOR/article/details/115532116