简体   繁体   中英

Find the content of a TextBox inside a DataTemplate with multiple rows

I have this code:

<StackPanel>
<ItemsControl ItemsSource="{Binding Position}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="2*" />
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="80" />
                </Grid.ColumnDefinitions>
                <TextBox Grid.Column="0" Text="{Binding Name}" Margin="5" />
                <TextBox Grid.Column="3" Text="{Binding ID}" Margin="5" />
                <Button Grid.Column="4" Content="X" Click="Delete" />
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

For example i have 3 rows. I want to delete the second row with it's elements. I click the Delete Button in the second Row and all i need is the ID inside the TextBox. If i get the ID in the code behind i can delete that Position from the Database. There is no problem if i have only one Row. In that case i give a name for the TextBox containing the ID and i can get the value in code behind. But how can i do this if i have 3,4,10 Positions each of them in a separate Row?

You may bind the Button's Tag to the ID property and access that in the Click handler:

<Button Grid.Column="4" Content="X" Click="Delete" Tag="{Binding ID}" />

Click handler:

private void Delete(object sender, RoutedEventArgs e)
{
    var button = (Button)sender;
    var id = (int)button.Tag;
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM