绑定到当前ItemsSource上下文之前的DataContext [英] Binding to DataContext outside current ItemsSource context
问题描述
我有一个 DataSet
绑定到 Window.DataContext
;我还有一个 DataGrid
:
I have a DataSet
bound to the Window.DataContext
; I also have a DataGrid
:
<DataGrid ItemsSource={Binding Tables[Items]}>
<DataGrid.Columns>
<DataGridTextBoxColumn Header={Binding Path=DataContext.Tables[Names]/Test, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}} />
</DataGrid.Columns>
</DataGrid>
基本上,我试图将该列的标题绑定到DataTableNames,Column测试,第一行。
Basically, I'm trying to bind the Header of that column to DataTable "Names", Column "Test", first row.
但是,我无法得到正确的。请注意,我可以在DataGrid之外绑定它。 Grid的ItemsSource会更改数据上下文,我不知道如何引用原来的DataContext。
However, I can't get it right. Note that I can bind it fine outside the DataGrid. The Grid's ItemsSource changes the data context and I don't know how to refer outside to the original DataContext.
似乎绑定成功;但是问题是Window.DataContext中的Tables [Names]的当前项目(第一行)丢失了。
It seems that the binding succeeds; but the problem is that the current item (first row) of the Tables[Names] in the Window.DataContext got lost.
如果我让DataSet静态访问它通过{x:Static local:dataset}然后事情工作正常。但是我不能使用静态数据集,因为会有多个实例(多用户)。
If I make the DataSet static and access it via {x:Static local:dataset} then things work fine. But I can't use static datasets because there will be multiple instances (multi-user).
任何人都可以指向正确的方向?
Can anyone please point me in the right direction?
推荐答案
我很确定你可以使用 RelativeSource
绑定
I'm pretty sure you could do what you're trying to do by using RelativeSource
binding.
<DataGrid ItemsSource="{Binding StringCollection}"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding}" />
<DataGridTextColumn Binding="{
Binding RelativeSource={
RelativeSource FindAncestor,
AncestorType={x:Type Window}},
Path=DataContext.SomethingOutsideDataContext}" />
</DataGrid.Columns>
</DataGrid>
我做了一个简单的例子: http://bitbucket.org/claus/wpf-bindingoutsidedatacontext
I made a quick example at: http://bitbucket.org/claus/wpf-bindingoutsidedatacontext
它允许你绑定到父窗口,在我的例子中有viewmodel作为datacontext(在它上面有SomethingOutsideDataContext属性)。
It allows you to bind to the parent Window, which in my case has the viewmodel as datacontext (with the SomethingOutsideDataContext property on it).
你应该知道,这只能用于WPF,而不是Silverlight - FindAncestor,AncestorType的东西还没有在Silverlight中实现...我不知道还有另外一种方法,除了使用静态资源。
You should be aware though, this will only work with WPF and not Silverlight - the 'FindAncestor, AncestorType' stuff has not been implemented in Silverlight yet... I'm not sure if there's another method, besides using static resources.
这篇关于绑定到当前ItemsSource上下文之前的DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!