c# - 如何在 WPF C# 中的 ItemsControl 中获取项目值?
问题描述
单击 ItemsControl 项目时,我想从 ItemsControl 获取项目值。
下面是我的示例代码:
<ItemsControl x:Name="ListViewProducts" ItemsSource="{Binding Product}" PreviewMouseLeftButtonUp="listView_Click" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Margin="10" Width="110" Height="160">
<StackPanel>
<Border Width="100" Height="100" CornerRadius="5" Margin="5">
<Border.Effect>
<DropShadowEffect ShadowDepth="1"/>
</Border.Effect>
<Border.Background>
<ImageBrush ImageSource="{Binding Image}" />
</Border.Background>
</Border>
<!--<TextBlock Margin="5" Text="{Binding Value, StringFormat={}{0:C}}" FontSize="17" FontFamily="Franklin Gothic Medium"/>-->
<TextBlock Margin="5 0" Text="{Binding Name}" FontSize="15"/>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
代码隐藏:
private void listView_Click(object sender, RoutedEventArgs e)
{
var item = (sender as ItemsControl);
if (item != null)
{
}
}
但这不起作用,我没有得到项目的详细信息。请帮助我。
我只需要使用 Itemcontrol。当我使用 listview 时,它显示列表不是正确的方式,所以我使用了 itemscontrol。请看下面的图片。当我使用列表视图时,它显示为一个框。请找到截图。
解决方案
您可以定义一个并处理容器的事件,PreviewMouseLeftButtonUp
而不是处理。然后,您可以简单地将参数转换为您的类型:ItemsControl
ItemContainerStyle
PreviewMouseLeftButtonDown
DataContext
sender
private void ContentControl_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var product = ((FrameworkElement)sender).DataContext as Product;
...
}
XAML:
<ItemsControl x:Name="ListViewProducts" ItemsSource="{Binding Product}" >
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="ContentControl_PreviewMouseLeftButtonDown" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
...
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
...
</ItemsControl.ItemsPanel>
</ItemsControl>
或者为in处理PreviewMouseLeftButtonDown
事件并做同样的事情。Border
ItemTemplate
推荐阅读
- android - 使用 Realm 和 Parcel 将 API 响应存储在两个不同的模型对象中
- html - 网格布局未显示
- r - 在 R 中按特定顺序排序数据
- c++ - 序列化人脸特征以在 DLIB 中进行识别
- django - Django:无法解析 /accounts/password_reset/ 上的关键字“is_active”
- javascript - 在渲染方法 [REACT NATIVE] 中访问此变量
- mysql - SQL查询统计图片并获取封面图片
- javascript - 如何以角度调用外部jQuery函数
- caching - Angular 和 ASP .NET MVC 的缓存
- ajax - 如果数据实际上安全地传递到服务器,网站是否需要 SSL?