WPF ListView的每行按键 [英] WPF ListView with buttons on each line

查看:157
本文介绍了WPF ListView的每行按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆