WPF 数据网格 [System.Windows.Data 错误:4]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15548662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:13:10  来源:igfitidea点击:

WPF Datagrid [System.Windows.Data Error: 4]

c#wpfdatagrid

提问by RayOldProf

I have a WPF application with a DataGridas shown below:

我有一个 WPF 应用程序,DataGrid如下所示:

Datagrid (simplified):

数据网格(简化):

<DataGrid x:Name="CoreServiceLogDataGrid"
Grid.Row="0"
Height="auto"
ItemsSource="{Binding Source={StaticResource CoreServiceCollection}}"
AutoGenerateColumns="False"
CanUserReorderColumns="True"
CanUserSortColumns="True"
IsReadOnly="True">

    <DataGrid.Columns>
        <DataGridTextColumn x:Name="ID"
            Header="ID"
            Binding="{Binding ID}" />

        <DataGridTextColumn Binding="{Binding Timestamp}"
            Header="Timestamp" />

    </DataGrid.Columns>

</DataGrid>

when the Data is loaded; I get the following Error (numerous times):

加载数据时;我收到以下错误(多次):

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1''. BindingExpression:Path=AreRowDetailsFrozen; DataItem=null; target element is 'DataGridDetailsPresenter' (Name=''); target property is 'SelectiveScrollingOrientation' (type 'SelectiveScrollingOrientation')
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1''. BindingExpression:Path=HeadersVisibility; DataItem=null; target element is 'DataGridRowHeader' (Name=''); target property is 'Visibility' (type 'Visibility')

I have No Idea why this occurs and how to FIX this.

我不知道为什么会发生这种情况以及如何解决这个问题。

EDIT: (Info about CoreServiceLogViewCollection)

编辑:(关于 CoreServiceLogViewCollection 的信息)

CoreServiceCollection is just a ListCollectionView.

CoreServiceCollection 只是一个 ListCollectionView。

  public static ListCollectionView CoreServiceLogViewCollection {
        get {
            if (_coreServiceCollection == null) {
                _coreServiceCollection =
                    new ListCollectionView(LogSession.CoreServiceLogCollection);
            }

            return _coreServiceCollection;
        }
    }

the parameter is just an ObservableCollectioncontaining ID,Timestampand other properties

参数只是一个ObservableCollection含有IDTimestamp和其它性质

EDIt2: The instantiation is done in App.xaml:

EDit2:实例化在 App.xaml 中完成:

   <ResourceDictionary>
       <x:Static Member="vm2:CoreServiceLogView.CoreServiceLogViewCollection"
                          x:Key="CoreServiceCollection" />
   </ResourceDictionary>

EDIT 3 (The Style... )

编辑 3(风格...)

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                mc:Ignorable="d">


<!-- #columnHeaderDGStyle -->


<!-- Datagrid -->
<Style x:Key="Log4NetDataGridStyle"
       TargetType="DataGrid">

    <Setter Property="ColumnHeaderStyle"
            Value="{DynamicResource DatagridColumnHeaderCustomTemplateStyle}" />


    <Setter Property="RowStyle"
            Value="{DynamicResource Log4NetRowStyle}" />

    <Setter Property="RowDetailsTemplate"
            Value="{DynamicResource RowDetailsTemplate}" />

    <Setter Property="MaxHeight"
            Value="1600">
    </Setter>
    <Setter Property="MaxWidth"
            Value="2560">
    </Setter>


</Style>


<Style x:Key="DataCommuGridStyle"
       TargetType="DataGrid">

    <Setter Property="ColumnHeaderStyle"
            Value="{DynamicResource DatagridColumnHeaderCustomTemplateStyle}" />


    <Setter Property="RowStyle"
            Value="{DynamicResource CommuRowStyle}" />

    <Setter Property="RowDetailsTemplate"
            Value="{DynamicResource RowDetailsTemplate}" />

    <Setter Property="MaxHeight"
            Value="1600">
    </Setter>
    <Setter Property="MaxWidth"
            Value="2560">
    </Setter>


</Style>


<!-- ************************* Row Style ************************* -->
<Style x:Key="Log4NetRowStyle"
       TargetType="DataGridRow">

    <Setter Property="FontSize"
            Value="14" />

    <Setter Property="Background"
            Value="{Binding Path=LogColour.ColorName}" />

    <Setter Property="Height"
            Value="Auto">
    </Setter>

    <Style.Triggers>
        <DataTrigger></DataTrigger>
    </Style.Triggers>

</Style>

<Style x:Key="CommuRowStyle"
       TargetType="DataGridRow">

    <Setter Property="FontSize"
            Value="14" />

    <Setter Property="Background"
            Value="Azure" />

    <Setter Property="Height"
            Value="Auto">
    </Setter>

    <Style.Triggers>
        <DataTrigger></DataTrigger>
    </Style.Triggers>

</Style>


<DataTemplate x:Key="RowDetailsTemplate">
    <Border BorderThickness="0"
            Padding="5" >


        <Border.Background>
            <LinearGradientBrush StartPoint="0,0"
                                 EndPoint="0,1" Opacity="0.2">
                <GradientStop Color="White"
                              Offset="0" />
                <GradientStop Color="Black"
                              Offset="1" />
            </LinearGradientBrush>

        </Border.Background>


        <!-- alternative with Expancer -->
        <Expander IsExpanded="True"
                  HorizontalAlignment="Left"
                  BorderThickness="1,1,1,5"
                  MaxHeight="300"
                  MaxWidth="900">

            <Expander.Header>
                <DockPanel>
                    <TextBlock FontSize="12"
                               Text="LoggingMessage: "
                               VerticalAlignment="Center" />
                </DockPanel>
            </Expander.Header>

            <Expander.Content>
                <ScrollViewer VerticalScrollBarVisibility="Auto"
                              HorizontalScrollBarVisibility="Auto"
                              CanContentScroll="True"
                              Style="{StaticResource LeftScrollViewer}">
                    <StackPanel Orientation="Vertical">

                        <TextBox FontSize="16"
                                 BorderThickness="0"
                                 IsReadOnly="True"
                                 Background="Transparent"
                                 Foreground="Black"
                                 TextWrapping="Wrap"
                                 Text="{Binding LoggingMessage, Mode=OneWay}" />
                    </StackPanel>
                </ScrollViewer>
            </Expander.Content>
        </Expander>


    </Border>


</DataTemplate>


<Style x:Key="GroupHeaderStyle"
       TargetType="{x:Type GroupItem}">
    <Setter Property="Margin"
            Value="0,0,0,5" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type GroupItem}">
                <Expander IsExpanded="False"
                          Background="#FF112255"
                          BorderBrush="#FF002255"
                          Foreground="Black"
                          BorderThickness="1,1,1,5">
                    <Expander.Header>
                        <DockPanel>
                            <TextBlock FontWeight="Bold"
                                       Foreground="White"
                                       Text="{Binding Path=Name}"
                                       Margin="5,0,0,0"
                                       Width="100" />
                            <TextBlock FontWeight="Bold"
                                       Foreground="White"
                                       Text="{Binding Path=ItemCount}" />
                        </DockPanel>
                    </Expander.Header>

                    <Expander.Content>
                        <ItemsPresenter />
                    </Expander.Content>
                </Expander>


            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


<!-- ******************** DataTemplate ******************** -->


</ResourceDictionary>

回答by Rachel

I wrote an answer a while back about how to read WPF binding errors. Basically, break down your error on the semi-colons and start reading it from the bottom up, and it should give you some idea where the binding error is:

不久前我写了一个关于如何阅读 WPF 绑定错误的答案。基本上,在分号上分解你的错误并从下往上开始阅读它,它应该让你知道绑定错误在哪里:

  • System.Windows.Data Error: 4 :
    • Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1''. BindingExpression:Path=AreRowDetailsFrozen;
  • DataItem=null;
  • target element is 'DataGridDetailsPresenter' (Name='');
  • target property is 'SelectiveScrollingOrientation' (type 'SelectiveScrollingOrientation')
  • System.Windows.Data 错误:4:
    • 无法找到引用“RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1''的绑定源。BindingExpression:Path=AreRowDetailsFrozen;
  • 数据项=空;
  • 目标元素是 'DataGridDetailsPresenter' (Name='');
  • 目标属性是“SelectiveScrollingOrientation”(类型“SelectiveScrollingOrientation”)

and

  • System.Windows.Data Error: 4 :
    • Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1''. BindingExpression:Path=HeadersVisibility;
  • DataItem=null;
  • target element is 'DataGridRowHeader' (Name='');
  • target property is 'Visibility' (type 'Visibility')
  • System.Windows.Data 错误:4:
    • 无法找到引用“RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1''的绑定源。BindingExpression:Path=HeadersVisibility;
  • 数据项=空;
  • 目标元素是 'DataGridRowHeader' (Name='');
  • 目标属性是“可见性”(类型“可见性”)

Reading from the bottom up, the first error is telling you

自下而上阅读,第一个错误告诉你

  • the property containing the binding causing the error is SelectiveScrollingOrientation
  • the UI object containing the problematic property is a DataGridDetailsPresenter, with no name specified
  • the DataContextbehind the UI object is null
  • the binding is trying to find a RelativeSourceof type DataGridso it can bind to the AreRowDetailsFrozenproperty, and its failing to find that RelativeSource
  • 包含导致错误的绑定的属性是 SelectiveScrollingOrientation
  • 包含有问题的属性的 UI 对象是 a DataGridDetailsPresenter,没有指定名称
  • DataContextUI 对象的背后是null
  • 绑定试图找到一个RelativeSource类型,DataGrid以便它可以绑定到该AreRowDetailsFrozen属性,但未能找到RelativeSource

So look through your code for something resembling this:

因此,请查看您的代码以查找类似于以下内容的内容:

<DataGridDetailsPresenter SelectiveScrollingOrientation="{Binding 
    Path=AreRowDetailsFrozen, 
    RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}" />

The second error is telling you

第二个错误告诉你

  • the property containing the binding causing the error is Visibility
  • the UI object containing the problematic property is a DataGridRowHeader, with no name specified
  • the DataContextbehind the UI object is null
  • the binding is trying to find a RelativeSourceof type DataGridso it can bind to the HeadersVisibilityproperty, and its failing to find that RelativeSource
  • 包含导致错误的绑定的属性是 Visibility
  • 包含有问题的属性的 UI 对象是 a DataGridRowHeader,没有指定名称
  • DataContextUI 对象的背后是null
  • 绑定试图找到一个RelativeSource类型,DataGrid以便它可以绑定到该HeadersVisibility属性,但未能找到RelativeSource

So look through your code for something resembling this:

因此,请查看您的代码以查找类似于以下内容的内容:

<DataGridRowHeader Visibility="{Binding 
    Path=HeadersVisibility, 
    RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}" />

Based on the code you posted, the first may be in your LeftScrollViewerstyle somewhere, and the 2nd is probably in your DatagridColumnHeaderCustomTemplateStyle

根据您发布的代码,第一个可能是您的LeftScrollViewer风格,第二个可能是您的DatagridColumnHeaderCustomTemplateStyle

If you have problems finding the error in your XAML, you can try running your application and inspecting it with a tool like Snoopthat will let you look at the VisualTree of a WPF application while it's running, and you should be able to find the exact binding error there so you can trace it back to the source in your XAML

如果您在 XAML 中发现错误时遇到问题,您可以尝试运行您的应用程序并使用Snoop 之类的工具检查它,该工具可让您在运行时查看 WPF 应用程序的 VisualTree,您应该能够找到准确的绑定错误,以便您可以将其追溯到 XAML 中的源

回答by Michael

This error occures in the ControlTemplate for the DataGridRow that contains both a DataGridRowHeader and a DataGridDetailsPresenter with the bindings mentioned above. I got the same issue for the .NET 4.5 DataGrid. It seems that both errors only occures when the DataGrid is using virtualization for it's items, you can try to disable it in your DataGrid. In my opinion it happens when a DataGridRow is somehow attached/detached from it's DataGrid during the virtualization and the binding then looses or still not find the relative binding targets to the DataGrid.

此错误发生在包含具有上述绑定的 DataGridRowHeader 和 DataGridDetailsPresenter 的 DataGridRow 的 ControlTemplate 中。我在 .NET 4.5 DataGrid 上遇到了同样的问题。似乎这两个错误仅在 DataGrid 对其项目使用虚拟化时才会发生,您可以尝试在 DataGrid 中禁用它。在我看来,当 DataGridRow 在虚拟化过程中以某种方式从它的 DataGrid 附加/分离时,就会发生这种情况,然后绑定丢失或仍然找不到 DataGrid 的相关绑定目标。