2010-08-03 70 views
3

我有一些问题需要从DataGrid中访问Window的DataContext。从DataGrid中访问Window的DataContext

DataGrid绑定到IBindingList的:

public IBindingList Items{ get; set; } 
    private void initItems() 
    { 
     //ItemFactory is a Linq2SQL Context, Items is the view of availabe Items 
     this.Items = this.ItemFactory.Items.GetNewBindingList(); 
    } 

从我的XAML中我试图让这些数据来填充一个ComboBox:

<DataGridComboBoxColumn Header="Typ" 
          DisplayMemberPath="Description" 
          SelectedValuePath="ItemID"  
          ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Mode=OneWay, Path=DataContext.Items, UpdateSourceTrigger=PropertyChanged}" /> 

但它不工作。我已经尝试了很多变体。 ComboBox不会被填充。
任何帮助非常感谢!

注:

在同一个窗口下面的组合框不工作:

<ComboBox x:Name="workingCombo" ItemsSource="{Binding Path=Items}" DisplayMemberPath="Description" SelectedValuePath="ItemID" /> 

回答

1

DataGridComboBoxColumn没有直接连接到可视化树,因此FindAncestor - 操作将失败(也DataContext将不会被继承)。

  • 最简单的解决方案是 创建一个ViewModel对于每一行,并在的ItemsSource 组合框提供在那里。
  • 使用DataGridTemplateColumn和放置ComboBoxDataTemplate帮助。
  • Here 是另一篇关于这个问题的文章。还请看this 的帖子。
+0

谢谢你这个好回答!我没有通过Google搜索找到这2个帖子。 - 对每行使用ViewModel的问题是我将BindingList直接绑定到DataGrid的ItemSource。 - 如果我必须使用DataGridTemplateColumn ..什么是DataGridComboBoxColumn的价值?猜测只能用于静态定义的集合。 明天我会尝试这项工作,然后在成功时将其标记为答案;)ty再次 – SwissCoder 2010-08-03 23:10:30

+0

当我在DataGridTemplateColumn中使用ComboBox时,它使用RelativePath – SwissCoder 2010-08-04 10:01:18

相关问题