1

For example, I have:

MainWindows.cs

public partial class MainWindow : Window { public List<Player> List; public MainWindow() { InitializeComponent(); List = new List<Player>() { new Player() {Id = 1, Name = "Tom"}, new Player() {Id = 2, Name = "Bob"}, new Player() {Id = 3, Name = "Any"}, }; comboBox1.DataContext = List; } public class Player { public string Name { get; set; } public int Id { get; set; } } } 

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

How I can (need to) set List as a DataContext from the XAML? (and delete "comboBox1.DataContext = List" from the code-behind)

2 Answers 2

2

unless you're using MVVM u don't need to do that, but in any case, use can create the List as a property of the window like so

public List<Player> List {get;set;} 

and then in XAML u can use RelativeSource to bind to the window:

<ComboBox ItemsSource="{Binding Path=List, RelativeSource={RelativeSource AncestorType=Window, Mode=FindAncestor}}" DisplayMemberPath="Name"/> 

alternatively, u can give a name to your window:

<Window .... x:Name="MyWindow" ..> 

and then use ElementName in the binding, like so:

<ComboBox ItemsSource="{Binding Path=List, ElementName=MyWindow}" DisplayMemberPath="Name"/> 
Sign up to request clarification or add additional context in comments.

Comments

2

Quick fix is setting your ComboBox's ItemsSource directly in code-behind (instead of DataContext), but in order to be able to use proper bindings you'll need a ViewModel or at least a XAML DataContext.

Also you should pick some more unique name than List for your List, like for example Players – it's good practice to use the plural form of the type of Objects in the List.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.