如何从列表框C#wpf中获取子元素
本文关键字:获取 元素 C#wpf 列表 | 更新日期: 2023-09-27 18:00:51
我正在列表框中创建一个图像列表,但我需要这些图像可以点击。
我遇到的问题是在单击图像时从子元素(textblock(中获取值。
我在网上找遍了,但找不到解决办法。
`
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel Grid.Column="0" Grid.Row="0" Margin="10" Grid.ColumnSpan="2">
<TextBlock FontFamily="Tunga" FontSize="30" Foreground="White" Text="WOW" />
<TextBlock FontFamily="Tunga" FontSize="25" Foreground="White" Text="Work Out Warz" />
</StackPanel>
<StackPanel Grid.Column="4" Grid.Row="0">
<TextBlock FontFamily="Tunga" FontSize="36" Foreground="White" Text="" Name="txtname" Height="45"/>
<TextBlock FontFamily="Tunga" FontSize="25" Foreground="White" Text="" Name="txtwowid" />
</StackPanel>
<Grid Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="5" >
<ListBox x:Name="LstImages" Background="Gray" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.PanningMode="HorizontalOnly" Cursor="Hand" SelectionChanged="LstImages_SelectionChanged" IsSynchronizedWithCurrentItem="True" >
<ListBox.ItemTemplate>
<DataTemplate>
<ListBoxItem>
<StackPanel Orientation="Vertical" Margin="10" >
<Button Click="Button_Click" >
<Image Source="{Binding img}" Height="250"/>
</Button>
<TextBlock Name="txtblname" Text="{Binding Title}" Foreground="White" FontSize="30" FontFamily="Tunga"/>
</StackPanel>
</ListBoxItem>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
`
为了获得所选项目,您可以将dataContext对象中的SelectedImage绑定到ListBox 的SelectedItem属性,该对象应该具有Title
和img
属性
<ListBox SelectedItem="{Binding Path=SelectedImage, Mode=TwoWay}" x:Name="LstImages" Background="Gray" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.PanningMode="HorizontalOnly" Cursor="Hand" SelectionChanged="LstImages_SelectionChanged" IsSynchronizedWithCurrentItem="True" >