Dennis
Dennis

Reputation: 215

ComboBox ItemsSource binding within a DataTemplate

I'm trying to bind a combobox to a list of items (ObservableCollection) on my viewmodel. If I use something like this on my view:

<ComboBox ItemsSource="{Binding Path=Teams}" DisplayMemberPath="TeamName" />

everything is OK. But if I take that same combobox and use it as part of a datatemplate on another template used as the items template for a listbox, nothing shows up in the list. Pseudocode example:

<DataTemplate x:Key="test">
  <TextBlock Text="Team:" />
  <ComboBox ItemsSource="{Binding Path=Teams}" DisplayMemberPath="TeamName" />
</DataTemplate>
<ListBox ItemsSource="GamesCV" ItemTemplate="{StaticResource test}" />

I thought maybe I needed to add a relative source so I tried that, but no luck. I also tried giving my UserControl a name and using that as the ElementName on my combobox binding. I can't imagine this is as hard as I'm making it. I'm probably missing something obvious. Can anyone help? I can give more specifics if necessary, I'm just pressed for time right now.

Thanks, Dennis

Upvotes: 3

Views: 14755

Answers (2)

dnxit
dnxit

Reputation: 7350

For UWP I got it like this

   <GridView x:Name="abc" ItemsSource="{Binding Path=DataContext.Companies,RelativeSource={RelativeSource Mode=TemplatedParent}}"></GridView>

Upvotes: 0

brunnerh
brunnerh

Reputation: 185290

Maybe you forgot the DataContext in the path? If you use RelativeSource you target a framework element and no longer the DataContext, so this should do it:

{Binding DataContext.Teams, RelativeSource={RelativeSource AncestorType=ListBox}}

Also if you have trouble with bindings check for errors, they will tell you all you need to know.

Upvotes: 4

Related Questions