I have a DataGridComboBoxColumn
in a DataGrid
in a WPF
project set like this:
Your issue is caused by DataGridColumns
: indeed they do not belong to the visual tree, so you cannot bind their properties to your DataContext
.
You can find here a solution based on a kind of freezable "DataContext proxy", since Freezable
objects can inherit the DataContext
even when they are not in the visual tree.
Now if you put this proxy in the DataGrid
's resources, it can be bound the the DataGrid
's DataContext
and can be retrieve by using the StaticResource
keyword.
So you XAML will become:
<DataGridComboBoxColumn Header="Master" SelectedItemBinding="{Binding MasterId}"
SelectedValueBinding="{Binding Id}" DisplayMemberPath="Id"
ItemsSource="{Binding Data.Masters, Source={StaticResource proxy}}" />
Where proxy
is the name of your resource.
I hope it can help you.
EDIT
I update my answer with the code copied from this link (because of @icebat's comment). This is the BindingProxy
class:
public class BindingProxy : Freezable
{
#region Overrides of Freezable
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
#endregion
public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
// Using a DependencyProperty as the backing store for Data. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}
Then in the XAML you need to add:
<DataGrid.Resources>
<local:BindingProxy x:Key="proxy" Data="{Binding}" />
</DataGrid.Resources>