如何将DataContext绑定到窗口资源中的ViewModel对象

时间:2012-09-12 14:03:30

标签: wpf mvvm binding datacontext

我正在尝试将usercontrol datacontext绑定到viewmodel对象。由于未知原因,将Window.Resources中的DataContext设置为结果

  

System.Windows.Data错误:3:找不到提供的元素   DataContext的。 BindingExpression:路径= AreaFilter;的DataItem = NULL;

在window.resources之外设置相同的datacontext是完美的。一段代码应该清除一切:

<Window>
<Window.Resources>
    <GridViewColumnCollection x:Key="eventColumns">
        <GridViewColumn DisplayMemberBinding="{Binding Path=Area}">
            <GridViewColumn.Header>
                <v:FilterV DataContext="{Binding AreaFilter}"/> <!--here is the problem-->
            </GridViewColumn.Header>
        </GridViewColumn>
    </GridViewColumnCollection>
</Window.Resources>
<Grid>
    <v:FilterV DataContext="{Binding AreaFilter}"/> <!-- here it works OK -->
    <GridViewHeaderRowPresenter Name="listHeader" Columns="{StaticResource eventColumns}"/>
</Grid>

FilterV是我目前简化为仅显示文本块的UserControl。 在网格内部,它显示AreaFilter.Name没有问题。 在这两种情况下设置DataContext以及如何解决这个问题有什么区别?

1 个答案:

答案 0 :(得分:2)

我认为GridViewColumn实际上不是VisualTree的一部分,因此它中的绑定将无效,因为它在评估绑定时没有DataContext或源使用

您可以尝试使用引用DataContext的{​​{1}}绑定设置RelativeSource

GridView

虽然如果这不起作用,我发现的唯一解决方法是在<GridViewColumn.HeaderTemplate> <DataTemplate> <v:FilterV DataContext="{Binding DataContext.AreaFilter, RelativeSource={RelativeSource AncestorType={x:Type GridView}}}"/> </DataTemplate> </GridViewColumn.HeaderTemplate> 中创建包含您正在寻找的绑定的Freezeable对象,然后设置{{1}到静态资源

.Resources

您可以查看此here

的示例

此外,您应该将v:FilterV.DataContext属性设置为包含<GridView.Resources> <local:BindingProxy x:Key="proxy" Data="{Binding AreaFilter, ElementName=MyGridView}" /> </DataGrid.Resources> ... <GridViewColumn.HeaderTemplate> <DataTemplate> <v:FilterV DataContext="{Binding Source={StaticResource proxy}}"/> </DataTemplate> </GridViewColumn.HeaderTemplate> 控件的GridViewHeaderTemplate,而不是像现在一样直接在DataTemplate属性中设置它。将<v:FilterV />直接设置为对象意味着使用该样式的任何项目都将尝试在.Content中使用相同的控件,因此如果您有多个对象应用Content属性它将抛出异常,因为项只能属于一个父控件

相关问题