简体   繁体   中英

How can I bind the content of the combobox in xaml

<ComboBox Grid.Row="1" Margin="0,0,0,175" DataContext="{Binding }" />

I've set the DataContext of the xaml to a class.

Within in this I have a class called Player . A Player has a property array of another object called Quests . Each Quest has a name property.

How can I bind the content of the combobox to the Quest array, and have each item represented by its name property?

I'm assuming I will have to use binding

Never mind. Found out :D

If anyone else had the same problem:

Assume you have a List called Foos in your window / page. Foo has a property Name. Now you set up the binding in XAML as follows:

<ComboBox ItemsSource="{Binding Path=Foos}"
DisplayMemberPath="Name"
SelectedValuePath="Name"

Referenced from WPF Databinding combobox to a list<string>

  1. the statement DataContext="{Binding }" simply takes the current value of the DataContext property and assigns it back- this will have no effect.

  2. Assuming that the DataContext of this view has a property named Quests , what you need to do is:

     <ComboBox Grid.Row="1" Margin="0,0,0,175" ItemsSource="{Binding Quests}" /> 

Note that ComboBox derives from ItemsControl , and as such- setting the ItemsSource property will always do the trick.

You will probably need to create a data template for the quest item in order to see something of actual interest. This should get you started with Data Templates.

Once you've created a Data Template, set it to the ComboBox using the ItemTemplate property (Once more, a courtesy of ItemsControl ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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