WPF ListView的每行按键 [英] WPF ListView with buttons on each line
问题描述
我有一个List 游戏
这只是有一个 ID
,一个日期
和时间
。
我设置这个列表作为的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
为这些游戏是:
I then have a DataTemplate
for these games that is:
<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>
我需要一个按钮
添加到具有相同的单击事件查看该列表中的每一行,但会以某种方式通过游戏的哪个按钮是作为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
和订阅点击
事件
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>
在事件处理程序背后的code,就可以得到的DataContext
的点击按钮
并找到出了标识如
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屋!