16

WPF4.0 では、他のクラス タイプをプロパティとして含むクラスがあります (複数のデータ タイプを組み合わせて表示します)。何かのようなもの:

public partial class Owner
{
     public string OwnerName { get; set; }
     public int    OwnerId   { get; set; }
}

partial class ForDisplay
{
    public Owner OwnerData { get; set; }
    public int Credit { get; set; }
}

私のウィンドウには、次のような ItemsControl があります (わかりやすくするために切り取られています)。

<ItemsControl ItemsSource={Binding}>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
          <local:MyDisplayControl 
                OwnerName={Binding OwnerData.OwnerName}
                Credit={Binding Credit} />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

次に、データ レイヤーから表示情報のコレクションを取得し、DataContextItemsControlをこのコレクションに設定します。「Credit」プロパティは正しく表示されますが、OwnerName プロパティは表示されません。代わりに、バインディング エラーが発生します。

エラー 40: BindingExpression パス エラー: 'OwnerName' プロパティが 'object' ''ForDisplay' (HashCode=449124874)' に見つかりません。BindingExpression:Path=OwnerName; DataItem='ForDisplay' (HashCode=449124874); ターゲット要素は「TextBlock」(Name=txtOwnerName) です。ターゲット プロパティは 'Text' (タイプ 'String') です

ForDisplay OwnerData プロパティの Owner クラスではなく、ForDisplay クラスで OwnerName プロパティを検索しようとする理由がわかりません。

編集 カスタムコントロールの使用と関係があるようです。同じプロパティを にバインドすると、TextBlock正しく機能します。

<ItemsControl ItemsSource={Binding}>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
          <StackPanel>
              <local:MyDisplayControl 
                        OwnerName={Binding OwnerData.OwnerName}
                        Credit={Binding Credit} />
              <TextBlock Text="{Binding OwnerData.OwnerName}" />
              <TextBlock Text="{Binding Credit}" />
          </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
4

1 に答える 1

10

ここに投稿したコードは、ソリューションで使用しているコードですか?なぜなら、このコードは私のために働くからです:

XAML

<ItemsControl ItemsSource="{Binding}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding OwnerData.OwnerName}"></TextBlock>
                <TextBlock Text="{Binding Credit}" />
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

ウィンドウのロードされたイベント

ObservableCollection<ForDisplay> items = new ObservableCollection<ForDisplay>();

for (int i = 0; i < 10; i++)
{
    items.Add(new ForDisplay() { OwnerData = new Owner() { OwnerId = i + 1, OwnerName = String.Format("Owner #{0}", i + 1) }, Credit = i + 1 });
}

DataContext = items;
于 2010-06-17T15:37:32.607 に答える