i have a button inside a data-template , i want to access this button click event , to be more specific this data template contains a border and inside the border there is a button , i need to know which button is clicked to fetch some data dependent on the button tag

here is my xaml code

<DataTemplate x:Key="CityItemTemplate"  >
    <Border BorderBrush="Black" BorderThickness="4" CornerRadius="8" Background="#FF003847" Width="320">
        <StackPanel Margin="4">
            <TextBlock x:Name="NameBlock" TextWrapping="NoWrap" Text="{Binding Content}" FontSize="38" VerticalAlignment="Center" Margin="0,0,4,0"  Grid.Column="1" TextTrimming="WordEllipsis"/>
            <TextBlock x:Name="DescriptionBlock" TextWrapping="Wrap" Text="{Binding Description}" FontSize="24" VerticalAlignment="Center" Margin="0,0,4,0" Grid.Column="1" TextTrimming="WordEllipsis" MaxHeight="168"/>
                <Button   x:Name="b12" Content="download&#xD;&#xA;" HorizontalAlignment="Left" VerticalAlignment="Top" Width="166" Height="87" Tag="{Binding idb}" Click="{Binding btnData_Click}"  />
        </StackPanel>
    </Border>
</DataTemplate>
有帮助吗?

解决方案

Update your Button's click handler

<Button Click="Button_Click"  />

Access Button's tag in code

private void Button_Click(object sender, RoutedEventArgs e)
{
   var tag = (sender as Button).Tag;

   //do tag dependent work
}

Side Note: Button_click is called for any button clicked inside your data-binding but sender will be the specific instance of the clicked button that's why you can access all of its properties.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top