简体   繁体   English

将每个对象的某些变量显示到组合框中

[英]Display certain variable of each object into a Combobox

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. 我想将List<Whatever>链接到ComboxBox,用户可以在其中看到每个Whatever对象的Name How can I do that? 我怎样才能做到这一点?

You could either use ComboBox.ItemTemplate like this: 您可以像这样使用ComboBox.ItemTemplate

C#: C#:

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

XAML: XAML:

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

Or use DisplayMemberPath : 或使用DisplayMemberPath

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

Or just override the ToString() function and it will do the job for you: 或者只是重写ToString()函数,它将为您完成这项工作:

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;
}

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 根据Model-View-Modelview模式

This is more suited if you wan't to make changes based on user input. 如果您不想根据用户输入进行更改,则此方法更适合。 (Which is kinda rare for a combobox). (对于组合框而言,这种情况很少见)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM