Caliburn Micro - 将ListBox绑定到集合中对象的属性

时间:2014-09-12 08:33:01

标签: c# wpf caliburn.micro

我无法将列表框的ItemsSource绑定到对象集合,然后将这些对象的属性显示为列表项。

我的XAML代码:

<Window 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"
    mc:Ignorable="d"
    x:Class="CaliburnMicroBasic.ShellView"
    d:DesignWidth="358" d:DesignHeight="351">

<Grid Width="300" Height="300" Background="LightBlue">   
    <ListBox ItemsSource="{Binding ListOfPeople}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding PersonName}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>
</Window>

我的ViewModel:

namespace CaliburnMicroBasic {
using Caliburn.Micro;
using System.Collections.ObjectModel;
using System.Windows;

public class ShellViewModel :  Screen, IShell
{
    public Person SelectedPerson{ get; private set; }
    public ObservableCollection<Person> ListOfPeople{ get; private set; }

    public ShellViewModel()
    {
        ListOfPeople = new ObservableCollection<Person>();
        ListOfPeople.Add(new Person("Name 1"));
        ListOfPeople.Add(new Person("Name 2"));
        ListOfPeople.Add(new Person("Name 3"));
        ListOfPeople.Add(new Person("Name 4"));
    }
}

public class Person
{
    public string PersonName { get; private set; }

    public Person(string personName)
    {
        _personName = personName;
    }
}
}

正如您所看到的,我正在尝试让列表框使用Person.PersonName作为列表框中每个文本块的内容,但我所得到的只是列表框中的四个空行。换句话说,列表框包含正确数量的项目,但没有一个项目正确呈现。

谁能看到我做错了什么?

1 个答案:

答案 0 :(得分:2)

您永远不会为PersonName属性分配任何内容。将您的代码更改为:

   public Person(string personName)
    {
        this.PersonName  = personName;
    }

并删除您的私人字段。

相关问题