您的问题是由以下原因引起的DataGridColumns
: 确实是他们不属于视觉树,所以你不能将它们的属性绑定到你的DataContext
.
你可以找到here基于一种可冻结的“DataContext代理”的解决方案,因为Freezable
对象可以继承DataContext
即使它们不在视觉树中。
现在,如果您将此代理放入DataGrid
的资源,可以绑定DataGrid
's DataContext
并可以通过使用来检索StaticResource
关键词。
所以你的 XAML 将变成:
<DataGridComboBoxColumn Header="Master" SelectedItemBinding="{Binding MasterId}"
SelectedValueBinding="{Binding Id}" DisplayMemberPath="Id"
ItemsSource="{Binding Data.Masters, Source={StaticResource proxy}}" />
Where proxy
是您的资源的名称。
我希望它可以帮助你。
EDIT
我用从中复制的代码更新我的答案link(因为@icebat的评论)。这是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));
}
然后在XAML中你需要添加:
<DataGrid.Resources>
<local:BindingProxy x:Key="proxy" Data="{Binding}" />
</DataGrid.Resources>