嵌套的DataContext

时间:2012-11-09 00:38:49

标签: wpf binding datacontext nested

我在以下代码(DataContextsDataContext)中有2个嵌套ItemsSource

<TabItem Header="Something" Name="myTabItemName" d:DataContext="{Binding myViewModel}">
    <Grid>
        <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding muObservableCollection}" Name="myDataGridName" HeadersVisibility="Column">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Foo 01" Binding="{Binding Foo_01}" />
                <DataGridTextColumn Header="Foo 02" Binding="{Binding Foo_02}" />
                <DataGridTemplateColumn Header="My custom combobox">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <!-- Here I want to bind back to 'myViewModel's' myProperty. I've tried this way: -->
                            <ComboBox ItemsSource="{Binding Path=myProperty, RelativeSource={RelativeSource AncestorType={x:Type TabItem}}}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</TabItem>

我想将myViewModel(返回)分配给ComboBox's DataContext。问题是ComboBox已在行中“覆盖”DataContext

<DataGrid ItemsSource="{Binding muObservableCollection}" ... >

我该怎么做?

1 个答案:

答案 0 :(得分:2)

<ComboBox ItemsSource="{Binding Path=DataContext.myProperty, RelativeSource={RelativeSource AncestorType={x:Type TabItem}}}" />

应该做的伎俩。但是我想指出你想要的东西没有意义:你绑定你的TabItem让我们说顺序实例,DataGrid绑定到它的Orderlines,为什么你想要DataGrid中的Order组合框? Al列将显示相同的值,如果更改一行,则所有行的值都会更改。

我自己遇到过这种情况,我需要访问更高级别(由于重构与命令相结合),但这种情况相当罕见。