WPF DataGrid和DataGridTemplateColumn标头问题

时间:2013-10-14 16:22:40

标签: c# wpf xaml mvvm datagrid

我的一段代码存在问题......

我有如下内容:

<DataGrid AutoGenerateColumns="False"
          CanUserAddRows="False"
          CanUserDeleteRows="False"
          ItemsSource="{Binding Path=RowData,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          RowHeaderWidth="0">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.Header>
                <CheckBox IsChecked="{Binding RelativeSource={RelativeSource Findancestor, AncestorType={x:Type UserControl}},Path=DataContext.AreAllSelected}">
                    Select All
                </CheckBox>
            </DataGridTemplateColumn.Header>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding Path=IsSelected,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>  
    <DataGrid.Columns>
</DataGrid>

它是在一个View中,它是从UserControl类型派生出来的 - 绝对可以肯定。由于某种原因,绑定在TemplateColumn标头中的CheckBox上失败。有什么不寻常之处在于我在其他视图中使用了这个代码 - 它的工作原理非常好并且没有任何问题。我总是首先创建ViewModel,并将其作为参数传递给View,其中DataContext在构造时设置为ViewModel,即

View(ViewModel myViewModel)
{
   InitializeComponent();
   DataContext = myViewModel;
}

ViewModel上有AreAllSelected属性,但是我收到以下错误 - 所以我知道它由于某种原因找不到祖先。

  

System.Windows.Data错误:4:找不到绑定源   参考'RelativeSource FindAncestor,   AncestorType = 'System.Windows.Controls.UserControl',   AncestorLevel = '1'”。 BindingExpression:路径= DataContext.AreAllSelected;   的DataItem = NULL; target元素是'CheckBox'(Name ='');目标财产   是'IsChecked'(类型'Nullable`1')

奇怪的是,即使它不起作用,当我使用Snoop查看它时,它最初也不起作用。当我查看Binding并深入研究它时,Binding现在可以正常工作。

我想知道它是如何在Visual Tree级别构建的或者是什么?正如我之前所说 - 我在其他视图中已经完成了其他几次,并且它们工作正常。必须有一些奇怪的事情,我做错了......

1 个答案:

答案 0 :(得分:3)

尝试相反的方式:

View(ViewModel myViewModel)
{
   DataContext = myViewModel;
   InitializeComponent();
}

顺便说一句,你应该使用HeaderTemplate模板标题。单独的标题只能是一个字符串值。

您放置了CheckBox。这不是wpf的通常方式。

相关问题