WPF:绑定到ObservableCollection中类的属性



我有一个类叫Robot:

public class Robot
{
public string name { get; private set; }
public Robot(string robotName)
{
name = robotName;
}
}

我在ModelView中创建了这个类的ObservableCollection:

public ObservableCollection<Robot> Robots { get; private set; } = new ObservableCollection<Robot>();

我现在需要绑定这个ObservableCollection到我的ListView,但我需要属性name绑定到ListView,而不是类转换为字符串。

<ListView ItemsSource="{Binding Robots}" />

我该怎么做?

设置DisplayMemberPath属性为项目属性的名称:

<ListView ItemsSource="{Binding Robots}" DisplayMemberPath="name" />

Robot属性应该被命名为Name-使用Pascal大小写来遵守广泛接受的命名约定:

public class Robot
{
public string Name { get; }
public Robot(string name)
{
Name = name;
}
}

XAML将是

<ListView ItemsSource="{Binding Robots}" DisplayMemberPath="Name" />

最新更新