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

本文关键字:数据 误差 Windows System 数据网 网格 WPF | 更新日期: 2023-09-27 18:05:01

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

Datagrid ()简化:

<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>

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

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')

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

编辑:(Info about coreservicogviewcollection)

CoreServiceCollection只是一个ListCollectionView。

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

参数只是一个包含IDTimestamp和其他属性的ObservableCollection

EDIt2:实例化在App.xaml:

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

编辑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>

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

我写了一篇关于如何读取WPF绑定错误的回答。基本上,将分号上的错误分解并从下往上阅读,它应该会让你知道绑定错误在哪里:

  • System.Windows。数据错误:4:
    • 无法找到与引用'RelativeSource '绑定的源FindAncestor, ancestor ='System.Windows.Controls '。DataGrid, AncestorLevel = 1"。BindingExpression:路径= AreRowDetailsFrozen;
  • DataItem =零;
  • 目标元素是'DataGridDetailsPresenter' (Name= " ");
  • 目标属性是'SelectiveScrollingOrientation'(类型'SelectiveScrollingOrientation')

  • System.Windows。数据错误:4:
    • 无法找到与引用'RelativeSource '绑定的源FindAncestor, ancestor ='System.Windows.Controls '。DataGrid, AncestorLevel = 1"。BindingExpression:路径= HeadersVisibility;
  • DataItem =零;
  • 目标元素是'DataGridRowHeader' (Name= ");
  • 目标属性为"可见性"(类型为"可见性")

从下往上读,第一个错误是告诉你

    包含导致错误的绑定的属性是SelectiveScrollingOrientation
  • 包含有问题属性的UI对象是一个DataGridDetailsPresenter,没有指定名称
  • UI对象后面的DataContextnull
  • 绑定试图找到DataGrid类型的RelativeSource,以便它可以绑定到AreRowDetailsFrozen属性,并且未能找到RelativeSource

所以仔细检查你的代码,看看是否有类似这样的东西:

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

第二个错误告诉你

  • 包含导致错误的绑定的属性是Visibility
  • 包含有问题属性的UI对象是一个DataGridRowHeader,没有指定名称
  • UI对象后面的DataContextnull
  • 绑定试图找到DataGrid类型的RelativeSource,因此它可以绑定到HeadersVisibility属性,并且无法找到RelativeSource

所以仔细检查你的代码,看看是否有类似这样的东西:

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

根据你发布的代码,第一个可能是在你的LeftScrollViewer风格的地方,第二个可能是在你的DatagridColumnHeaderCustomTemplateStyle

如果在XAML中查找错误有问题,可以尝试运行应用程序并使用Snoop之类的工具对其进行检查,该工具可以在运行时查看WPF应用程序的VisualTree,您应该能够在那里找到确切的绑定错误,以便您可以将其追溯到XAML

中的源。

这个错误发生在DataGridRow的ControlTemplate中,它包含了一个DataGridRowHeader和一个DataGridDetailsPresenter与上面提到的绑定。我在。net 4.5 DataGrid中遇到了同样的问题。似乎只有当DataGrid对其项目使用虚拟化时才会出现这两个错误,您可以尝试在DataGrid中禁用它。在我看来,当一个DataGridRow在虚拟化过程中以某种方式与它的DataGrid连接/分离,然后绑定丢失或仍然没有找到相对绑定目标到DataGrid时,就会发生这种情况。

我有一个DataGrid嵌套的DataGrid作为RowDetails。我也寻找了很长时间来解决这个问题的正确答案。

DataGridRow模板出现问题。只需寻找"数据网格样式和模板"即可。-并打开微软网站

如果你在那里寻找一个DataGridRow模板(text):DataGridRow的样式和模板。

你会发现这段代码:

 <SelectiveScrollingGrid>
        <SelectiveScrollingGrid.ColumnDefinitions>
          <ColumnDefinition Width="Auto" />
          <ColumnDefinition Width="*" />
        </SelectiveScrollingGrid.ColumnDefinitions>
        <SelectiveScrollingGrid.RowDefinitions>
          <RowDefinition Height="*" />
          <RowDefinition Height="Auto" />
        </SelectiveScrollingGrid.RowDefinitions>
        <DataGridCellsPresenter Grid.Column="1"
                                ItemsPanel="{TemplateBinding ItemsPanel}"
                                SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
        <DataGridDetailsPresenter Grid.Column="1"
                                  Grid.Row="1"
                                  Visibility="{TemplateBinding DetailsVisibility}"
                                  SelectiveScrollingGrid.SelectiveScrollingOrientation=
            "{Binding AreRowDetailsFrozen, 
            ConverterParameter={x:Static SelectiveScrollingOrientation.Vertical},
            Converter={x:Static DataGrid.RowDetailsScrollingConverter}, 
            RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
        <DataGridRowHeader Grid.RowSpan="2"
                           SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical"
                           Visibility="{Binding HeadersVisibility, 
            ConverterParameter={x:Static DataGridHeadersVisibility.Row}, 
            Converter={x:Static DataGrid.HeadersVisibilityConverter}, 
            RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
      </SelectiveScrollingGrid>

问题就在这里。

在寻找解决方案时,我发现了这个建议-以这种方式更改DataGridRow的样式:

  <Style TargetType="{x:Type DataGridRow}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="DataGridRow">
                            <Border BorderThickness="{TemplateBinding Border.BorderThickness}" BorderBrush="{TemplateBinding Border.BorderBrush}" Background="{TemplateBinding Panel.Background}" Name="DGR_Border" SnapsToDevicePixels="True">
                                <SelectiveScrollingGrid>       
                                    <DataGridCellsPresenter ItemsPanel="{TemplateBinding ItemsControl.ItemsPanel}" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}"/>   
                                </SelectiveScrollingGrid>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>   
            </Style>

它工作了,但是我的行细节不见了。在我从原始模板中添加了缺失的部分后:

 <SelectiveScrollingGrid.RowDefinitions>
          <RowDefinition Height="*" />
          <RowDefinition Height="Auto" />
        </SelectiveScrollingGrid.RowDefinitions>
        <DataGridCellsPresenter Grid.Column="1"
                                ItemsPanel="{TemplateBinding ItemsPanel}"
                                SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
        <DataGridDetailsPresenter Grid.Column="1"
                                  Grid.Row="1"
                                  Visibility="{TemplateBinding DetailsVisibility}"
                                  SelectiveScrollingGrid.SelectiveScrollingOrientation=
            "{Binding AreRowDetailsFrozen, 
            ConverterParameter={x:Static SelectiveScrollingOrientation.Vertical},
            Converter={x:Static DataGrid.RowDetailsScrollingConverter}, 
            RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>

我又得到这个错误。所以目标是改变这部分:

<DataGridDetailsPresenter Grid.Column="1"
                                  Grid.Row="1"
                                  Visibility="{TemplateBinding DetailsVisibility}"
                                  SelectiveScrollingGrid.SelectiveScrollingOrientation=
            "{Binding AreRowDetailsFrozen, 
            ConverterParameter={x:Static SelectiveScrollingOrientation.Vertical},
            Converter={x:Static DataGrid.RowDetailsScrollingConverter}, 
            RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>

到固定值,像这样:

 <DataGridDetailsPresenter Grid.Column="1"
                                  Grid.Row="1"
                                  Visibility="{TemplateBinding DetailsVisibility}"
                                  SelectiveScrollingGrid.SelectiveScrollingOrientation="Both"/>

或者你可以这样命名你的DataGrid:

 <SelectiveScrollingGrid>
                                    <SelectiveScrollingGrid.RowDefinitions>
                                        <RowDefinition Height="*" />
                                        <RowDefinition Height="Auto" />
                                    </SelectiveScrollingGrid.RowDefinitions>
                                    <DataGridCellsPresenter ItemsPanel="{TemplateBinding ItemsControl.ItemsPanel}" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}"/>
                                    <DataGridDetailsPresenter  Grid.Row="1"
                                    Visibility="{TemplateBinding DetailsVisibility}"
                                    SelectiveScrollingGrid.SelectiveScrollingOrientation=
                                    "{Binding ElementName=MainDataGrid,Path=AreRowDetailsFrozen, ConverterParameter={x:Static SelectiveScrollingOrientation.Vertical},
                                     Converter={x:Static DataGrid.RowDetailsScrollingConverter}}"/>
                                </SelectiveScrollingGrid>

注意,我已经删除了RowHeaders部分,因为我不使用它

对于在数据网格上使用过滤的任何人:

我在我的数据网格上使用GroupStyle,必须添加

DataGrid.GroupStyle.Clear();