无法访问列表框中的选定图像
.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'值。
答案 0 :(得分:0)
您的Image
控件位于Button.Content
属性中,而不是Button.DataContext
属性中。此外,Image
控件不是Bitmap
。试试这个:
Image image = ((Button)sender).Content as Image;
或者,如果您只想访问图像文件路径:
var imageFile = ((Button)sender).DataContext as string;