WPF System.Windows.Data Error: 4  実行時エラーの解消法

huahi11115 455 評価のポイント
2025-05-27T11:04:06.22+00:00

イラスト

VB.net WPFでプログラムを作成中です。

Visual studio version 2019

(xaml)

   <Window x:Class="MainWindow"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:local="clr-namespace:WpfApp1"

    Title="MainWindow" Height="360" Width="784">

<Window.Resources>

    <Style TargetType="local:Myclass1">

        <Setter Property="Template">

            <Setter.Value>

                <ControlTemplate TargetType="local:Myclass1">

                    <ContentPresenter HorizontalAlignment="Left" VerticalAlignment="Center"/>

                </ControlTemplate>

            </Setter.Value>

        </Setter>

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

    </Style>

</Window.Resources>

<Grid Margin="0,0,22,19" VerticalAlignment="Top">

    <ListBox x:Name="LI3" ScrollViewer.HorizontalScrollBarVisibility="Visible"

             HorizontalAlignment="Left" Height="98" Margin="53,188,0,0"

             VerticalAlignment="Top" Width="180"/>

    <CheckBox x:Name="CX2" Content="ooo" HorizontalAlignment="Left"

              Margin="180,89,0,0" VerticalAlignment="Top" Width="105"

              FontSize="14" IsChecked="True"/>

</Grid>
</Window>
(VB.net)

vb
Imports System.Collections.ObjectModel

Imports System.Windows.Threading

Class MainWindow
Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded

    Dim l2 As New List(Of Myclass1)

    Dim i As Integer

    For i = 0 To 6 '1回のループでは、実行時エラーは発生しない

        Dim item As New Myclass1 With {

            .Content = i.ToString  ' ListBoxItem の Content プロパティに値を設定

        }

        l2.Add(item)

    Next

    'エラーの内容

    'System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'Myclass1' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')

    'System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'Myclass1' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')

    'System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'Myclass1' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')

    'System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'Myclass1' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')

    Me.LI3.ItemsSource = l2

End Sub
End Class

Class Myclass1

Inherits ListBoxItem
Public Property b1 As Boolean 'ダミー
End Class






```以上

forループを1回にすると実行時エラーは発生しません。

エラーが発生しない様に解決法を教えて下さい。

開発者向けテクノロジ .NET その他
{count} 件の投票

承認済みの回答
  1. gekka 12,206 評価のポイント MVP ボランティア モデレーター
    2025-05-28T03:53:18.2766667+00:00

    ループが1回だろうが7回だろうが関係なく、ListBoxItemにContentを設定して初期化するだけで発生するものです。

    Dim item = New ListBoxItem With {.Content = ""}
    

    ListBoxItemが生成されるときにListBoxItemのテーマStyleが適用されて、その適用されたStyleにあるSetterでHorizontalContentAlignmentとVerticalContentAlignmentにバインディングが設定されます。
    このバインディングはRelativeSource AncestorTypeでLitBoxItemの親をさかのぼってItemsControl(=ListBox)を探すようになっています。

    ListBoxがVirtualizingPanelを使用して仮想化していると、表示範囲外になっているListBoxItemは実際には配置されず、配置されていないので親が無く、そのためItemsControlも見つかりません。
    つまり、エラーメッセージにあるように、このバインディングでItemsControlが見つかりませんでしたというエラーです。

    # Contentが設定されると大きさや配置の計算が発生するからかもしれない


    このエラーを出したくないのであれば、

    • 仮想化をさせない。
    <ListBox x:Name="LI3" VirtualizingPanel.IsVirtualizing="false" />
    

    あるいは、Contentの設定をスタイルの適用と生成が終わった後に遅延させる

    Dim l2 As New List(Of Myclass1)
    Dim i As Integer
    For i = 0 To 6
        Dim item As New Myclass1() 'With {.Content = i.ToString}
        AddHandler item.Loaded, Sub(s, e)
                                    item.Content = i.ToString()
                                End Sub
        l2.Add(item)
    Next
    

    あるいはデフォルトで適用されるスタイルを適用させない。

    Dim item As New Myclass1() With {.OverridesDefaultStyle = True, .Content = i.ToString}
    
    1 人がこの回答が役に立ったと思いました。
    0 件のコメント コメントはありません

1 件の追加の回答

並べ替え方法: 最も役に立つ
  1. huahi11115 455 評価のポイント
    2025-05-28T08:25:22.2333333+00:00
    御回答誠にありがとうございました。
    こちらでの確認結果ですが、
    >ループが1回だろうが7回だろうが関係なく、ListBoxItemにContentを設定して初期化するだけで発生するものです。
    と、ありますが、ループを1回にすると、発生確率は激減します。ループ回数6回以上でエラーが発生するようになります。
    PCの性能にも関係があるのかも知れませんが、WPFの内部処理とのタイミングが原因で発生しているように見えます。
    まず、
    <ListBox x:Name="LI3" VirtualizingPanel.IsVirtualizing="false" />
    ↑この方法ですが、投稿したサンプルプログラムではエラーが表示されなくなる効果がありましたが、ListBoxItemを継承した自作クラスに多くの容量を積載していくと、これでもエラーが出るようになりました。
    次に、Dim item As New Myclass1() With {.OverridesDefaultStyle = True, .Content = i.ToString} の御回答から
    自作クラスのコンストラクターにme.OverridesDefaultStyle = True を設定することで、現在はエラーが発生しなくなっています。
        AddHandler item.Loaded, Sub(s, e)
                                    item.Content = i.ToString()
                                End Sub
    ↑この方法は、次の対策として検討させていただきます。
    動作したプログラムのソースを掲載します。
    《xaml》
    <Window x:Class="MainWindow"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp1"
        Title="MainWindow" Height="360" Width="784">
        <Window.Resources>
            <Style TargetType="local:Myclass1">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="local:Myclass1">
                            <ContentPresenter HorizontalAlignment="Left" VerticalAlignment="Center"/>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
                <Setter Property="Height" Value="18"/>
            </Style>
        </Window.Resources>
        <Grid Margin="0,0,22,19" VerticalAlignment="Top">
            <ListBox x:Name="LI3" ScrollViewer.HorizontalScrollBarVisibility="Visible"
                 HorizontalAlignment="Left" Height="98" Margin="53,188,0,0" VirtualizingPanel.IsVirtualizing="false"
                 VerticalAlignment="Top" Width="180"/>
            <CheckBox x:Name="CX2" Content="ooo" HorizontalAlignment="Left"
                  Margin="180,89,0,0" VerticalAlignment="Top" Width="105"
                   FontSize="14" IsChecked="True"/>
        </Grid>
    </Window>
    《VB》
    Imports System.Collections.ObjectModel
    Imports System.Windows.Threading
    Class MainWindow
       Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
          Dim l2 As New List(Of Myclass1)
          Dim i As Integer
          For i = 0 To 6 '1回のループでは、実行時エラーは発生しない
             Dim item As New Myclass1 With {.Content = i.ToString}
             l2.Add(item)
          Next
          'エラーは解消された
          'System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'Myclass1' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')
          'System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'Myclass1' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')
          'System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'Myclass1' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')
          'System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'Myclass1' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')
          Me.LI3.ItemsSource = l2
       End Sub
       Private Sub CX2_Checked(sender As Object, e As RoutedEventArgs) Handles CX2.Checked
          Dim l2 As New List(Of Myclass1)
          Dim i As Integer
          For i = 0 To 6 '1回のループでは、実行時エラーは発生しない
             Dim item As New Myclass1 With {.Content = i.ToString}
             l2.Add(item)
          Next
          Me.LI3.ItemsSource = l2
       End Sub
    End Class
    Class Myclass1
       Inherits ListBoxItem
       Public Property b1 As Boolean 'ダミー
       Public Sub New()
          Me.OverridesDefaultStyle = True '対策
       End Sub
    End Class
    
    0 件のコメント コメントはありません

お客様の回答

回答は、質問作成者が [承諾された回答] としてマークできます。これは、ユーザーが回答が作成者の問題を解決したことを知るのに役立ちます。