WPF ListView with buttons on each line

后端 未结 3 2124
渐次进展
渐次进展 2020-12-04 22:40

I have a list of Games which just has an ID, a Date, and a Time. I am setting this list as the DataContext.<

相关标签:
3条回答
  • 2020-12-04 22:51

    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>
    

    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;
        // ...
    }
    
    0 讨论(0)
  • 2020-12-04 22:54

    With a ListBox.ItemTemplate. Then in your click event you can get the object via DataContext.

        <ListBox.ItemTemplate>
            <DataTemplate>
                <Button Content="^" IsEnabled="{Binding Path=IsNotFirst, Mode=OneWay}" 
                 Click="btnMoveFDAup"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    
    
        private void btnMoveFDAup(object sender, RoutedEventArgs e)
        {
            Button btn = ((Button)sender);
            // btn.DataContext will get you to the row object where you can retrieve the ID
        }
    
    0 讨论(0)
  • 2020-12-04 23:05

    Easily. Add a Button to your DataTemplate, give it a Command and then set the CommandParameter="{Binding}". The DataContext within a DataTemplate is the object.

    As requested, some links to using commands.

    • WPF Commands Part 1: Basics
    • WPF Commands Part 2: Command Bindings and Gestures
    • MSDN Understanding Routed Events and Commands In WPF (ADVANCED)

    HTH,

    0 讨论(0)
提交回复
热议问题