访问动态添加的图像到wpf中的列表框
本文关键字:列表 wpf 图像 动态 添加 访问 | 更新日期: 2023-09-27 18:25:38
无法访问列表框中的所选图像
.xml代码:
<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"值。
您的Image
控件位于Button.Content
属性中,而不是Button.DataContext
属性中。此外,Image
控件不是Bitmap
。试试这个:
Image image = ((Button)sender).Content as Image;
或者如果您只想访问图像文件路径:
var imageFile = ((Button)sender).DataContext as string;