WPF - 引用事件中的类成员 [英] WPF - referencing a class member in an event
问题描述
我有一组包含图像的类和这些图像的路径:
I have a collection of classes that hold images and the paths of those images:
public ObservableCollection<Item> PictureList { get; set; }
public class Item
{
public ImageSource picture { get; set; }
public string fullName { get; set; }
}
我使用列表框来显示图像。
I am using a listbox to display the images.
<ListBox Height="Auto"
Width="200"
Margin="0"
ItemsSource="{Binding PictureList}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Source="{Binding picture}"
Height="100"
Width="100"
MouseUp="Picture_Click"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我希望能够做的是参考
属性,但是由于图像绑定到 Picture_Click
事件中的fullName 图片
我不能弄清楚如何访问 fullName
属性。
我用谷歌搜索但没有运气来解决这个问题。
这方面的任何帮助都很受欢迎。
What I would like to be able to do is reference the fullName
property in the Picture_Click
event, however as the image is bound to picture
I cannot figure out how to access the fullName
property.
I have googled but had not luck in working this out.
Any help on this much appreciated.
推荐答案
你不需要Button
,只需引用Image
的DataContext
,类似于你所做的:
You don't need theButton
, just reference theDataContext
of theImage
similar to what you did:
private void Picture_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(((Item)(((Image)sender).DataContext)).fullName);
}
应该工作。
Ought to work.
我通过将图像包装在一个按钮内来修复它:
I fixed it by wrapping the image inside a button:
<listbox height="Auto">
Width="200"
Margin="0"
ItemsSource="{Binding PictureList}">
<listbox.itemtemplate>
<datatemplate>
<stackpanel>
<button background="Transparent">
Click="Button_Click">
<image source="{Binding picture}">
Height="100"
Width="100"/>
</image></button>
</stackpanel>
</datatemplate>
</listbox.itemtemplate>
</listbox>
使用 Button_Click
方法然后我引用 fullName
property。
WIthin the Button_Click
method I then reference the fullName
property.
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(((Item)(((Button)sender).DataContext)).fullName);
}
这不是很好,任何人都有更优雅的解决方案请在这里发布 - 谢谢。
It's not pretty so anyone with a more elegant solution please post it here - thanks.
这篇关于WPF - 引用事件中的类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!