如何在DataGrid.DataGridTemplateColumn中设置UserControl的DataContext?

时间:2012-06-21 05:35:41

标签: wpf mvvm user-controls wpfdatagrid datacontext

我想在DataGridTemplateColumn中设置usercontrol的datacontext,但它不起作用,这是代码:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding RequesterPeoples}">
<DataGrid.Columns>
    <DataGridTemplateColumn  Header="name" Width="200">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <MvvmCommonControl:CustomDataGridSelectorControl DataContext="{Binding DataContext.RequesterPeoplesDataContext,ElementName=MyWindow}">
                    <MvvmCommonControl:CustomDataGridSelectorControl.DataGridColumns>
                        <MvvmCommonControl:DataGridColumnCollection>
                            <DataGridTextColumn Header="FarsiNmae" Width="100" Binding="{Binding FarsiName, Mode=OneWay}"></DataGridTextColumn>
                        </MvvmCommonControl:DataGridColumnCollection>
                    </MvvmCommonControl:CustomDataGridSelectorControl.DataGridColumns>
                </MvvmCommonControl:CustomDataGridSelectorControl>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>

1 个答案:

答案 0 :(得分:3)

我只需要使用RelativeSource代替ElementName

我改变了这个:

 DataContext="{Binding DataContext.RequesterPeoplesDataContext,ElementName=MyWindow}"

到此:

 DataContext="{Binding DataContext.RequesterPeoplesDataContext,RelativeSource={RelativeSource AncestorType=Window}}"