スタック パネル ビューのビュー モデルを作成します。このビュー モデルでブロック ビュー モデルのコレクションを公開します。
このコレクションをビューのスタック パネル内の ItemsControl のようなものにバインドします。ユーザー コントロールを使用してすべての項目を表示するように、テンプレートを設定します。
ItemsControl によってインスタンス化されたすべてのコントロールは、コレクションの要素に関連付けられます。これにより、独自のビュー モデルに関連付けられたすべてのユーザー コントロールが作成されます。
更新 - ここにいくつかのコードがあります
メインページ:
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel Orientation="Vertical">
<ItemsControl ItemsSource="{Binding BlockViewModels}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:BlockView></local:BlockView>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Grid>
メインページのコードビハインド:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
DataContext = new MainPageViewModel();
}
}
メイン ページ ビュー モデル:
public class MainPageViewModel
{
public ObservableCollection<BlockViewModel> BlockViewModels
{
get;
private set;
}
public MainPageViewModel()
{
BlockViewModels = new ObservableCollection<BlockViewModel>();
BlockViewModels.Add(new BlockViewModel { CurrentBlock = new Block { Name = "Block 1", Price = 10 } });
BlockViewModels.Add(new BlockViewModel { CurrentBlock = new Block { Name = "Block 2", Price = 20 } });
}
}
ブロック モデル:
public class Block
{
public string Name
{
get;
set;
}
public int Price
{
get;
set;
}
}
ブロック ビュー モデル:
public class BlockViewModel
{
public Block CurrentBlock
{
get;
set;
}
}
ブロック ビュー:
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding CurrentBlock.Name}"></TextBlock>
<TextBlock Text=" - "></TextBlock>
<TextBlock Text="{Binding CurrentBlock.Price}"></TextBlock>
</StackPanel>
</Grid>