【问题标题】:Caliburn Micro - bind ListBox to property of objects in a collectionCaliburn Micro - 将 ListBox 绑定到集合中对象的属性
【发布时间】:2014-09-12 08:33:00
【问题描述】:

我无法将列表框的 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>

我的视图模型:

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 作为列表框中每个文本块的内容,但我得到的只是列表框中的四个空行。换句话说,列表框包含正确数量的项目,但没有一个项目被正确呈现。

谁能看出我做错了什么?

【问题讨论】:

  • 只是在这些情况下获取更多数据的提示:检查调试输出,看看是否有一些行,例如“找不到与引用绑定的源...”。他们可以帮助您找到问题所在。您还可以在数据绑定上将调试跟踪级别设置为高以获取更多信息。见wpftutorial.net/DebugDataBinding.html

标签: c# wpf caliburn.micro


【解决方案1】:

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

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

并删除您的私有字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    相关资源
    最近更新 更多