每行带有按钮的 WPF ListView [英] WPF ListView with buttons on each line
问题描述
我有一个 Games
列表,其中只有一个 ID
、一个 Date
和一个 Time
.我将此列表设置为 DataContext
.
I have a list of Games
which just has an ID
, a Date
, and a Time
.
I am setting this list as the DataContext
.
然后我有这些游戏的DataTemplate
:
<DataTemplate DataType="{x:Type loc:Game}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition Width="100"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Name="dateBlock" Grid.Column="0" Grid.Row="1"
Text="{Binding Date, StringFormat=d}"></TextBlock>
<TextBlock Name="TimeBlock" Grid.Column="1" Grid.Row="1"
Text="{Binding Time}"></TextBlock>
//need to but a button here for each row
</Grid>
</DataTemplate>
要使用模板,我只是这样做:
To use the template, I am simply just doing this:
<ListBox ItemsSource="{Binding}"></ListBox>
我需要向列表视图中具有相同点击事件的每一行添加一个 Button
,但会以某种方式传递点击按钮的游戏的 ID.
I need to add a Button
to each line in this list view that have the same click event, but will somehow pass the ID of the game for which button is being clicked.
我该怎么做?我被困住了.如果它没有意义,请告诉我,我会尽力解释得更好.
How can I do this? I am stuck. If it doesn't make sense let me know and I will try to explain better.
推荐答案
对于第一部分,在 DataTemplate
中添加一个 Button
并订阅 Click
事件
For the first part, add a Button
to the DataTemplate
and subscribe to the Click
event
<DataTemplate DataType="{x:Type loc:Game}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition Width="100"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Name="dateBlock" Grid.Column="0" Grid.Row="1" Text="{Binding Date, StringFormat=d}"></TextBlock>
<TextBlock Name="TimeBlock" Grid.Column="1" Grid.Row="1" Text="{Binding Time}"></TextBlock>
<Button Click="Button_Click">X</Button>
</Grid>
</DataTemplate>
在事件处理程序背后的代码中,您可以获取点击的Button
的DataContext
并找出Id like
In the code behind event handler, you can get the DataContext
of the clicked Button
and find out the Id like
private void Button_Click(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
Game game = button.DataContext as Game;
int id = game.ID;
// ...
}
这篇关于每行带有按钮的 WPF ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!