WPF Datagrid [System.Windows.Data错误:4] [英] WPF Datagrid [System.Windows.Data Error: 4]

查看:122
本文介绍了WPF Datagrid [System.Windows.Data错误:4]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



Datagrid( / em>):

 < 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
标题=ID
Binding ={Binding ID}/>

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

< /DataGrid.Columns>

< / DataGrid>

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

  System.Windows.Data错误:4:找不到与引用绑定的源'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.DataGrid',AncestorLevel ='1''。 BindingExpression:Path = AreRowDetailsFrozen; DataItem = null; target元素是'DataGridDetailsPresenter'(Name ='');目标属性是'SelectiveScrollingOrientation'(类型'SelectiveScrollingOrientation')
System.Windows.Data错误:4:找不到与引用'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.DataGrid',AncestorLevel = '1''。 BindingExpression:Path = HeadersVisibility; DataItem = null; target元素是'DataGridRowHeader'(Name ='');目标属性是可见性(类型可见性)

我没有想法为什么会发生这种情况,到FIX这个。



编辑:(关于CoreServiceLogViewCollection的信息)



CoreServiceCollection只是一个ListCollectionView。

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

return _coreServiceCollection;
}
}

参数只是一个含有 ID 时间戳和其他属性


$的ObservableCollection
b $ b

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

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

编辑3(风格...)



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


<! - *************************行风格****** ******************* - >
< 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,1Opacity =0.2>
< GradientStop Color =White
Offset =0/>
< GradientStop Color =Black
Offset =1/>
< / LinearGradientBrush>

< /Border.Background>


<! - 替代与Expancer - >
< Expander IsExpanded =True
Horizo​​ntalAlignment =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
Horizo​​ntalScrollBarVisibility =Auto
CanContentScroll =True
Style ={StaticResource LeftScrollViewer}>
< StackPanel Orientation =Vertical>

< TextBox FontSize =16
BorderThickness =0
IsReadOnly =True
背景=透明
前景=黑色
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
背景=#FF112255
BorderBrush =#FF002255
前景=黑色
BorderThickness =1, 1,1,5>
< Expander.Header>
& DockPanel>
< TextBlock FontWeight =Bold
Foreground =White
Text ={Binding Path = Name}
Margin =5,0,0,0
宽度=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.Data错误:4:


    • 找不到与引用'RelativeSource FindAncestor,AncestorType ='System.Windows绑定的源代码。 Controls.DataGrid',AncestorLevel ='1''。 BindingExpression:Path = AreRowDetailsFrozen;


  • DataItem = null;

  • target元素是'DataGridDetailsPresenter'(Name ='');

  • target属性为'SelectiveScrollingOrientation'(键入'SelectiveScrollingOrientation')






  • System.Windows.Data错误:4:


    • 找不到源代码绑定参考'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.DataGrid',AncestorLevel ='1''。 BindingExpression:Path = HeadersVisibility;


  • DataItem = null;

  • target元素是'DataGridRowHeader'(Name ='');

  • 目标属性是可见性(类型可见性)



从底部读取第一个错误告诉你




  • 包含导致错误的绑定的属性是 SelectiveScrollingOrientation

  • 包含有问题的属性的UI对象是一个 DataGridDetailsPresenter ,没有指定名称

  • UI对象之后的 DataContext null

  • 绑定试图找到类型 DataGrid RelativeSource ,以便它可以绑定到 AreRowDetailsFrozen 属性,它未能找到 RelativeSource



所以看看你的代码的东西类似于:

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

第二个错误告诉你




  • 包含导致错误的绑定的属性是可见性

  • 包含有问题的属性的UI对象是 DataGridRowHeader ,没有指定名称

  • UI对象后面的 DataContext null

  • 绑定试图找到一个 RelativeSource 类型 DataGrid ,所以它可以绑定到 HeadersVisibility 属性,并且没有找到 RelativeSource



所以看看你的代码是否像这样:

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

根据您发布的代码,第一个可能在您的 LeftScrollViewer style某处,第二个可能在你的 DatagridColumnHeaderCustomTemplateStyle



如果你有问题找到您的XAML中的错误,您可以尝试运行应用程序并使用 Snoop 等工具进行检查看一下WPF应用程序的VisualTree运行时,您应该能够找到确切的绑定错误,以便您可以将其追溯到XAML中的源代码


I have a WPF application with a DataGrid as shown below:

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)

CoreServiceCollection is just a ListCollectionView.

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

            return _coreServiceCollection;
        }
    }

the parameter is just an ObservableCollection containing ID,Timestamp and other properties

EDIt2: The instantiation is done in App.xaml:

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

EDIT 3 (The Style... )

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

解决方案

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:

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

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

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 DataContext behind the UI object is null
  • the binding is trying to find a RelativeSource of type DataGrid so it can bind to the AreRowDetailsFrozen property, and its failing to find that 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 DataContext behind the UI object is null
  • the binding is trying to find a RelativeSource of type DataGrid so it can bind to the HeadersVisibility property, and its failing to find that 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 LeftScrollViewer style somewhere, and the 2nd is probably in your DatagridColumnHeaderCustomTemplateStyle

If you have problems finding the error in your XAML, you can try running your application and inspecting it with a tool like Snoop that 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

这篇关于WPF Datagrid [System.Windows.Data错误:4]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆