绑定到祖先的Datacontext

最好先向我展示我的代码,然后提出问题:

        

我有DataGridComboBoxColumn并希望将ItemsSource绑定到Window的DataContext ,并将SelectedItem绑定到DataGrid的当前ItemsSource对象。

如何才能做到这一点 ?

谢谢!

要避免使用您必须熟悉NameScope的ElementName,您还可以使用FindAncestor。 在这里,您可以定义要绑定到的父对象的类型。

例:

  

使用ElementName绑定表达式。 这将允许您从绑定表达式中按名称引用窗口。

http://msdn.microsoft.com/en-us/library/system.windows.data.binding.elementname.aspx

这里解释了用法。

http://www.wpfdude.com/articles/BindingToElement.aspx

          

请注意,如果每个Printer.PrinterType不直接引用Window的DataContext中存在的项,则需要覆盖.Equals()类的.Equals()方法以使这两个项相等。

就像是

 public override bool Equals(object obj) { if (obj == null) return false; if (this.GetType() != obj.GetType()) return false; PrinterType printerType= (PrinterType)obj; return (this.Id == printerType.Id); } 

现在我找不到其他方法来做这个比在运行时设置itemssource这样:

 private void SetComboBoxItemssource() { PrinterTypes = database.GetPrinterTypes(); DataGridComboBoxColumn cmbColumn = null; foreach (DataGridColumn column in dtaPrinters.Columns) { if ((cmbColumn = column as DataGridComboBoxColumn) != null) break; } if (cmbColumn == null) return; cmbColumn.ItemsSource = PrinterTypes; } 

它虽然有效..

我只能将此工作绑定到窗口的资源:

  

我无法使用RelativeSources,FindAncestors等。

以下对我有用。 只是想发布它,因为我使用的答案被粘贴到fix_likes_codes的答案的评论中。 关键是在路径中的属性名称前面添加DataContext前缀。