/ / ItemsControl ItemTemplateバインディング - wpf、バインディング、.net-4.0、itemscontrol、itemtemplate

ItemsControl ItemTemplateバインディング - wpf、バインディング、.net-4.0、itemscontrol、itemtemplate

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"プロパティが見つかりません 「オブジェクト」「ForDisplay」の場合 (HashCode = 449124874) "#:。 BindingExpression:パス= OwnerName。 DataItem = "ForDisplay" (HashCode = 449124874);ターゲット要素 "TextBlock"(Name = txtOwnerName ")です。 ターゲットプロパティは "Text"(タイプ "文字列")

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>

回答:

回答№1の場合は7

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

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;