0

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

我的 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离开列表包含所有正确的数据,我的列表框显示为空白,但其中包含正确数量的对象离开(我可以选择它们)但没有显示文本。我有这个味精:

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')

有人可以帮忙吗??

4

1 回答 1

0

您正在尝试绑定到字段 ( leaveNameand numberOfDays) 而不是属性 ( LeaveNameand NumberOfDays),这在 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>

此外,您可能应该继续制作字段private(leaveNamenumberOfDays) 而不是public.

于 2013-06-20T03:18:26.403 回答