次の方法で共有

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

huahi11115 620 評価のポイント
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 | その他
開発者テクノロジ | .NET | その他

.NET ソフトウェア フレームワークに基づく Microsoft テクノロジ。 特定のカテゴリに適合しないその他のトピック。


質問作成者が受け入れた回答

  1. gekka 13,986 評価のポイント 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 件の追加の回答

並べ替え方法: 最も役に立つ

お客様の回答

質問作成者は回答に "承認済み"、モデレーターは "おすすめ" とマークできます。これにより、ユーザーは作成者の問題が回答によって解決したことを把握できます。