我按以下方式绑定项目:
<ScrollViewer>
<ItemsControl x:Name="UserList">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Source="{Binding imageurl}"
Tag="{Binding Path=id}" Width="164" Height="150"
Margin="4" Stretch="Fill"></Image>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
Code.cs:
List.Add(new StackImages { id = "1", Name="test",type="test",price ="testprice" ,imageurl = new Uri(this.BaseUri, @"Assets/acservice.png") });
List.Add(new StackImages { id = "2", imageurl = new Uri(this.BaseUri, @"Assets/brakes.png") });
List.Add(new StackImages { id = "3", imageurl = new Uri(this.BaseUri, @"Assets/carwash.png") });
List.Add(new StackImages { id = "4", imageurl = new Uri(this.BaseUri, @"Assets/oilchange.png") });
List.Add(new StackImages { id = "5", imageurl = new Uri(this.BaseUri, @"Assets/transmission.png") });
UserList.ItemsSource= List;
请点击它时告诉我如何获得特定标签值的特殊图像?
答案 0 :(得分:1)
基于answer given to your previous question,您有两种选择。您可以访问Image控件的Source
属性并将其强制转换为BitmapImage
(这是WPF通过从Uri
到ImageSource
的自动类型转换创建的内容):
private void MyTapHandler(Object sender, EventArgs e)
{
Image image = (Image)sender;
BitmapImage bitmap = (BitmapImage)image.Source;
Uri uri = bitmap.UriSource;
}
或者您可以访问图片StackImage
中的DataContext
对象:
private void MyTapHandler(Object sender, EventArgs e)
{
Image image = (Image)sender;
StackImage stackImage = (StackImage)image.DataContext;
Uri uri = stackImage.imageurl;
}
答案 1 :(得分:0)
您可能要做的是从列表中选择项目。为了支持选择,您必须将ItemsControl
替换为ListBox
。
<ListBox x:Name="UserList" SelectionMode="Single"
SelectionChanged="UserList_SelectionChanged">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Image Source="{Binding imageurl}"
Tag="{Binding Path=id}" Width="164" Height="150"
Margin="4" Stretch="Fill"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
现在,您可以将处理程序附加到SelectionChanged
事件,并且您可以随时通过SelectedItem
或SelectedIndex
属性访问所选项目。
private void UserList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedImage = UserList.SelectedItem as StackImage;
if (selectedImage != null)
{
var uri = selectedImage.imageurl;
}
}