问题
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