WPF将对象绑定到Listbox,文本没有出现

时间:2013-06-20 03:06:13

标签: wpf binding

我搜索过,找不到问题的答案,有人可以帮忙吗?我试图将对象列表绑定到列表框。我有正确数量的项目(我仍然可以选择它们),但我看不到文本。

我的Xaml代码:

<ListBox x:Name="listbox_leave" BorderThickness="0">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding leaveName}" />
                <TextBlock Text="{Binding numberOfDays}" />
            </StackPanel>
       </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

这是后端代码:

ObservableCollection<Leave> leavelist = new ObservableCollection<Leave>(); 
leavelist = DbControl.loadLeaveDetails();
listbox_leave.ItemsSource = leavelist;

和我的休假班:

class Leave
{
    public string leaveName;

    public string LeaveName
    {
        get { return leaveName; }
        set { leaveName = value; }
    }

    public string numberOfDays;

    public string NumberOfDays
    {
        get { return numberOfDays; }
        set { numberOfDays = value; }
    }
}

当我调试时,ObservableCollection Leave列表包含所有正确的数据,我的列表框显示为空白,但它有正确的对象数留在其中(我可以选择它们)但没有文本显示。我有这个消息:

System.Windows.Data Error: 40 : BindingExpression path error: 'leaveName' property not found on 'object' ''Leave' (HashCode=44930696)'. BindingExpression:Path=leaveName; DataItem='Leave' (HashCode=44930696); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

System.Windows.Data Error: 40 : BindingExpression path error: 'numberOfDays' property not found on 'object' ''Leave' (HashCode=44930696)'. BindingExpression:Path=numberOfDays; DataItem='Leave' (HashCode=44930696); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

System.Windows.Data Error: 40 : BindingExpression path error: 'leaveName' property not found on 'object' ''Leave' (HashCode=29274103)'. BindingExpression:Path=leaveName; DataItem='Leave' (HashCode=29274103); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

System.Windows.Data Error: 40 : BindingExpression path error: 'numberOfDays' property not found on 'object' ''Leave' (HashCode=29274103)'. BindingExpression:Path=numberOfDays; DataItem='Leave' (HashCode=29274103); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您尝试绑定字段(leaveNamenumberOfDays)而不是属性(LeaveNameNumberOfDays),WPF不支持此功能。

将其更改为:

<ListBox x:Name="listbox_leave" BorderThickness="0">
    <ListBox.ItemTemplate>
       <DataTemplate>
          <StackPanel>
             <TextBlock Text="{Binding LeaveName}" />
             <TextBlock Text="{Binding NumberOfDays}" />
          </StackPanel>
       </DataTemplate>
    </ListBox.ItemTemplate>
 </ListBox>

此外,您应该继续使用字段privateleaveNamenumberOfDays)而不是public