如何使用C#代码在多个xaml元素内部的堆栈面板中添加图像

时间:2014-06-14 12:26:50

标签: c# xaml visual-studio-2012 windows-phone-8

我有一个包含多个全景项目的xaml页面,其中一个全景代码如下

 <phone:PanoramaItem Header="onepan">

      <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
      <StackPanel>
      <ListBox x:Name="PhoneList" Height="486" Background="{x:Null}">
     <ListBox.ItemTemplate>
      <DataTemplate>

       <StackPanel Orientation="Horizontal" Height="108"  >
     <Image Height="100" Margin="5" Stretch="Fill" Width="100" Source="/Assets/ApplicationIcon.png" ></Image>
     <Grid x:Name="ContentPanel" Margin="20,28,0,0"  Width="265" >
      <Grid.RowDefinitions>
      <RowDefinition Height="Auto"/>
   <RowDefinition Height="Auto"/>
   <RowDefinition Height="Auto"/>
  </Grid.RowDefinitions>
 <TextBlock x:Name="titles" FontSize="30" FontWeight="Bold" TextWrapping="Wrap" LineHeight=" 24" MaxHeight=" 48" LineStackingStrategy="BlockLineHeight" Grid.Row="0" Foreground="Black" FontStyle="Normal" Text="{Binding title}" 
                                            Margin="0,0,0,0"  Tag="{Binding title}" Tap="navigateto"/>
  <TextBlock Grid.Row="2" VerticalAlignment="Top" TextWrapping="Wrap"  Margin="123,-3,0,0" Foreground="Black" FontStyle="Normal" Text="{Binding Date}" Height="27" />
    <TextBlock HorizontalAlignment="Left" Margin="0,-4,0,3" Grid.Row="2" TextWrapping="Wrap"  Text="date :" Width="118" Foreground="Black"/>
   <StackPanel x:Name="ivnod" Orientation="Horizontal" HorizontalAlignment="Right" Height="28" Margin="0,21,10,-33" Grid.Row="2" VerticalAlignment="Top" Width="255">
   <TextBlock TextWrapping="Wrap" Text="Rating" Width="64" Foreground="Black"/>
   //I want to add here a image tag by c# code
    </StackPanel>
   </Grid>
        </StackPanel>
        </DataTemplate>
       </ListBox.ItemTemplate> 
     </ListBox>
       </StackPanel>
      </Grid>

 </phone:PanoramaItem>

我想在堆栈面板中添加名为&#39; ivnod&#39;使用for循环我可以直接添加图像,但我不知道是否应该在指定堆栈面板之前指定所有这些元素,并且在使用此代码时它会显示错误

  Image img = new Image();
  img.Source = new BitmapImage(new Uri("/Assets/ApplicationIcon.png", UriKind.Relative));
  ivnod.Children.Add(img);//-->here ivnod displayed as "not available in current context"

1 个答案:

答案 0 :(得分:1)

您应该对Image进行控制,然后您可以将binding传递给TextBlock。你只需要在Binding中将Source传递给Image。这将完美地运作。

<StackPanel x:Name="ivnod" Orientation="Horizontal" HorizontalAlignment="Right" Height="28" Margin="0,21,10,-33" Grid.Row="2" VerticalAlignment="Top" Width="255">
     <TextBlock TextWrapping="Wrap" Text="Rating" Width="64" Foreground="Black"/>
     <Image Source="{Binding imgSource}"></Image>
</StackPanel>