Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在wpf中访问动态添加到列表框的图像_C#_Wpf - Fatal编程技术网

C# 在wpf中访问动态添加到列表框的图像

C# 在wpf中访问动态添加到列表框的图像,c#,wpf,C#,Wpf,无法访问列表框中的选定图像 .xaml代码: <ListBox x:Name="listBox" Margin="10,282,0,0" Grid.ColumnSpan="2"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <WrapPanel FlowDirection="LeftTo

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

.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代码中,即使在我单击图像后,文件“b1”仍显示“null”值。

您的
图像
控件位于
按钮.Content
属性中,而不是
按钮.DataContext
属性中。另外,
图像
控件不是
位图
。试试这个:

Image image = ((Button)sender).Content as Image;
或者,如果您只想访问图像文件路径:

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

按钮的
DataContext
中没有
Bitmap
。按钮的
内容
中有一个
图像
控件,从前面的问题中我们知道
数据上下文
中有一个文件路径字符串。在开始编写代码之前,我强烈建议大家仔细阅读一下这个主题(也许还有WPF的一般内容)。
System.Drawing.Image
也是错误的。这是一个好主意。开始阅读有关MSDN的文章。真正地你到底想对这张照片做什么?@Clemens是对的。。。你需要去做一些WPF阅读。虽然我不知道他为什么不加上他自己的答案而不是改变我的答案。克莱门斯,你的加入改变了我答案的意义,甚至没有意义,除非你读了他的另一篇文章,这篇文章甚至没有从这里链接到。错误编辑:(您的答案或多或少只是以前作为问题注释编写的内容的副本。但如果不添加此内容,则答案是不完整的,因为实际上不清楚OP将如何处理按钮中的图像。他或她是否要访问位图或图像文件?至少消息框标题提到了上载,所以我的答案是肯定的ss是访问文件并将其上传到某个地方并不是一个完全不现实的目的。不,你错了。这个问题名为
在wpf
中选择动态添加的图像到列表框中。它没有提到任何关于文件路径或
DataContext
的内容。事实上,我已经将你的编辑保留在适当的位置,所以请现在就放手。
var imageFile = ((Button)sender).DataContext as string;