将动态添加的图像访问到wpf中的列表框

时间:2013-07-30 09:58:56

标签: c# wpf

无法访问列表框中的选定图像

.xaml代码:

<ListBox x:Name="listBox" Margin="10,282,0,0" Grid.ColumnSpan="2">

                    <ListBox.ItemsPanel>
                    <ItemsPanelTemplate>
                        <WrapPanel FlowDirection="LeftToRight" ItemWidth="120" ItemHeight="120"/>
                    </ItemsPanelTemplate>
                </ListBox.ItemsPanel>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Button x:Name="b" Click="b_Click_1" Width="120" Height="120" >
                            <Image HorizontalAlignment="Left" 
                            Margin="-10,-10,-10,-10" 
                            x:Name="image1" 
                            Stretch="Fill" 
                            VerticalAlignment="Top" Source="{Binding}"
                        />
                        </Button>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

.cs代码:

   private void b_Click_1(object sender, RoutedEventArgs e)
    {
          try
        {
            MessageBoxResult a = MessageBox.Show("Are you want to upload", "Photo Upload", MessageBoxButton.OKCancel);
            if (a == MessageBoxResult.OK)
            {
 System.Drawing.Image b1 = (sender as Button).DataContext as System.Drawing.Image;
           }
        }
    }

在.cs文件的上述代码中,'b1'即使在我点击图像后也显示'null'值。

1 个答案:

答案 0 :(得分:0)

您的Image控件位于Button.Content属性中,而不是Button.DataContext属性中。此外,Image控件不是Bitmap。试试这个:

Image image = ((Button)sender).Content as Image;

或者,如果您只想访问图像文件路径:

var imageFile = ((Button)sender).DataContext as string;