0

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

.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”值。

4

1 回答 1

0

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

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

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

var imageFile = ((Button)sender).DataContext as string;
于 2013-07-30T10:18:00.910 回答