我使用了wrappanel和listbox在wp7上显示我的项目。但项目点击事件不起作用。我的代码如下
<Grid x:Name="ContentPanel" Grid.Row="1" Height="Auto">
<ListBox x:Name="lstDevice">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel>
<Button x:Name="btnData" >
<StackPanel Orientation="Vertical">
<Canvas
Width="175"
Height="175"/>
<TextBlock Text="{Binding Name}" Width="175" />
</StackPanel>
</Button>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
以上是设计代码,c#代码在
之下private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
lstDevice.ItemsSource = MainPage.user.dArray.ToList();
lstDevice.SelectionChanged += item_Select;
}
private void item_Select(object sender, SelectionChangedEventArgs e)
{
int p = ((ListBox)sender).SelectedIndex;
}
如何生成列表框项目选择事件并获取数字或某些属性以识别选择了哪个项目?提前谢谢!
答案 0 :(得分:1)
我认为这可能更适合你:
<Grid x:Name="ContentPanel" Grid.Row="1" Height="Auto">
<ListBox x:Name="lstDevice">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate >
<Button x:Name="btnData" Click="OnButtonClick" Tag="{Binding Name}" >
<StackPanel Orientation="Vertical">
<Canvas
Width="175"
Height="175"/>
<TextBlock Text="{Binding Name}" Width="175" />
</StackPanel>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
lstDevice.ItemsSource = MainPage.user.dArray.ToList();
}
private void OnButtonClick(object sender, RoutedEventArgs e)
{
Button b = (Button)sender;
var nameInTag=b.Tag.ToString();
}
答案 1 :(得分:0)
Make change in your xaml and cs code like this:
<Grid x:Name="ContentPanel" Grid.Row="1" Height="Auto">
<ListBox x:Name="lstDevice" SelectionChange="item_Select">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel>
<Button x:Name="btnData" >
<StackPanel Orientation="Vertical">
<Canvas
Width="175"
Height="175"/>
<TextBlock Text="{Binding Name}" Width="175" />
</StackPanel>
</Button>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
lstDevice.ItemsSource = MainPage.user.dArray.ToList();
}
private void item_Select(object sender, SelectionChangedEventArgs e)
{
var selctedItem = lstDevice.SelectedItem as (Your list box's itmsource)
}