Display certain variable of each object into a Combobox

别来无恙 提交于 2019-12-13 02:27:25

问题


Quick question..

I have a List of objects of this class:

public class Whatever
{
    public string Name { get; set; }
    public List<blaBla> m_blaBla { get; set; }
    // ..
}

And I want to link the List<Whatever> to a ComboxBox, where the user sees the Name of each Whatever object. How can I do that?


回答1:


You could either use ComboBox.ItemTemplate like this:

C#:

List<Whatever> lst = new List<Whatever>();
public MainWindow()
{
    InitializeComponent();
    cmb.ItemsSource = lst;
}

XAML:

<ComboBox Name="cmb">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Or use DisplayMemberPath:

<ComboBox Name="cmb" DisplayMemberPath="Name">            
</ComboBox>



回答2:


Or just override the ToString() function and it will do the job for you:

public class Whatever
{
    public string Name { get; set; }
    public List<blaBla> m_blaBla { get; set; }
    // ..
    public override string ToString()
    {
       return Name;
    }
}

And then:

List<Whatever> MyList = new List<Whatever>();
public MainWindow()
{
    InitializeComponent();
    MyComboBox.ItemsSource = MyList;
}



回答3:


Create a Viewmodel:

public ObservableCollection<Whatever> WhCol
{
    get { return this.Name; }
    set { }
}

And then a Matching View

<ComboBox DisplayMemberPath="Name" ItemsSource="{Binding WhCol}" />

According to Model-View-Modelview Pattern

This is more suited if you wan't to make changes based on user input. (Which is kinda rare for a combobox).



来源:https://stackoverflow.com/questions/37752103/display-certain-variable-of-each-object-into-a-combobox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!