スタックパネルの ..\Resources\ebi.png に保存されている画像を追加しようとしています。ほとんどの場合、テキスト ボックスの入力 "EtReqCount" に応じて、同じ画像が Stackpanel に表示されます。以下は、試したサンプルコードですが、エラーが発生しています
「指定されたビジュアルは、すでに別のビジュアルの子であるか、CompositionTarget のルートです」
以下は試したコードです。
private BitmapImage bmp = new BitmapImage(new Uri("WpfApplication1;component/Resources/ebi.png", UriKind.RelativeOrAbsolute));
private void EtReqCount_TextChanged(object sender, TextChangedEventArgs e)
{
StackPanel dynamicStackPanel = new StackPanel();
dynamicStackPanel.Width = 300;
dynamicStackPanel.Height = 200;
dynamicStackPanel.Background = new SolidColorBrush(Colors.LightBlue);
dynamicStackPanel.Orientation = Orientation.Vertical;
if (EtReqCount.Text != "")
{
for (int k = 1; k <= Int32.Parse(EtReqCount.Text); k++)
{
Image img = new System.Windows.Controls.Image(); // This makes the difference.
img.Source = bmp;
dynamicStackPanel.Children.Add(img);
}
}
}
XAML コード: