BindableCollection 显示字符串但从 ComboBox 获取 int

BindableCollection showing string but getting int from ComboBox

我有一个 BindableCollectio<string> 项目:

public BindableCollection<string> ProjectsList { get; set; }
public string SelectedProjectsList { get; set; } //project selected form combobox

目前我只有项目名称。我将该列表绑定到 WPF 中的简单 ComboBox

 <ComboBox x:Name="ProjectsList" SelectedValuePath="{Binding Path=SelectedProjectsList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

Project 模型看起来像这样:

public class Project
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }
}

PorjectsList中我只存储Project的名字。

我的问题是,我们可以从 BindableCollection 项目的 id 中检索并在组合框列表中仍然显示项目名称吗?或者在 CaliburnMicro?

中可能有更好的解决方案

您可以使用 SelectedValuePath and DisplayMemberPath 来达到目的。 您应该首先将 ProjectsList 属性 更改为 BindableCollection<Project>.

的类型
public BindableCollection<Project> ProjectsList { get; set; }
public int SelectedProjectsList { get; set; }

现在,你的Xaml

 <ComboBox ItemsSource="{Binding Path=ProjectsList}" DisplayMemberPath="Name" 
                  SelectedValue ="{Binding SelectedProjectsList, UpdateSourceTrigger=PropertyChanged}" 
                  SelectedValuePath="Id"/>

这将能够在组合框中显示 Name,同时在选择项目时显示 Id