Reputation: 900
I have a Datagrid that is bound to TeamMembers. In the code behind constructor:
public SetupView(SetupViewModel model)
{
InitializeComponent();
DataContext = model;
this.model = model;
ResourceGrid.ItemsSource = model.teamMembers;
ResourceGrid.DataContext = model;
}
My ViewModel :
public class SetUpViewModel {
Tasks = new ObservableCollection<string>() { "A", "B", "C", "D" };
}
In my XAML , My ResourceGrid is a Data grid that has one ComboBoxColumn :
<DataGridComboBoxColumn Header="Task" Width="115" ItemsSource="{Binding
Tasks}" ">
the Tasks in the binding refers to the Tasks Collection I declared in my view model. However when I run this it doesn work.
But if I do this where I add combo to Template column and then add items source of combobox to tasks on load combo , it works :
<DataGridTemplateColumn Header="Task" Width="115">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox Loaded="LoadATaskEventHandler"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
private void LoadATaskEventHandler(object sender, RoutedEventArgs e)
{
ComboBox comboBox = sender as ComboBox;
comboBox.ItemsSource=model.Tasks;
}
I dotn want to add combobox to template when datagrid supports comobocolumn. Please advise on this.
And what difference in performance and what is the best solution out of the two.
Upvotes: 0
Views: 163
Reputation: 388
the ComboBox has a different DataContext
than the rest of your view. Try:
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType = DataGrid}, Path=DataContext.Tasks}"
I think the difference in performance between the approaches is probably negligable, but doing it directly through bindings is better to avoid tight coupling.
Upvotes: 3