I have a button that contains an Image inside a grid, my problem is that I can't make the button Click
event work.
My XAML code:
....
<TabControl TabStripPlacement="Left">
<TabItem Loaded="ListProductsLoaded" Width="185" Height="100" Header="Lister les Produits">
<Grid Background="#FFE5E5E5">
<ListView Name="ProductsListView" IsHitTestVisible="False">
<ListView.View>
<GridView>
<GridViewColumn Width="120" Header="Reference" DisplayMemberBinding="{Binding ProductReference}"></GridViewColumn>
<GridViewColumn Width="150" Header="Nom" DisplayMemberBinding="{Binding ProductName}"></GridViewColumn>
<GridViewColumn Width="120" Header="Photo" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<Button PreviewMouseLeftButtonDown="ImageButtonLeftMouseButtonDown" Name="ImageButton" Width="120" Height="120" Click="ImageButtonClicked">
<Image Width="119" Height="119" Name="ProdImage" Source="{Binding ProductImage}"></Image>
</Button>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
</TabItem>
</TabControl>
....
As you can see I used two events, PreviewMouseLeftButtonDown
event and Click event, I used PreviewMouseLeftButtonDown
due to a solution I saw in a stackoverflow question but it didn't work. Both events methods display a MessageBox
private void ImageButtonClicked(object sender, RoutedEventArgs e)
{
MessageBox.Show(this, "clicked image button");
}
private void ImageButtonLeftMouseButtonDown(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("test clicked");
}
If anyone encountered this problem before please help me solve it, I searched for a solution without success. Thanks in advance.
Edit: Even if I use a normal button: No image in it, it doesn't work.
Solution : Actually, i set the Option IsHitTestVisible
of the TabControl
to false
and that disabled all Click
events… sorry everybody.
You can remove all event subscription from XAML and put it in code behind using compact syntax (just a single line of code) as shown below:
ImageButton.Click += (s, e) => { MessageBox.Show("test button clicked"); };
Also, REMOVE your event handling proc:
private void ImageButtonClicked(object sender, RoutedEventArgs e)
{
MessageBox.Show(this, "clicked image button");
}
In addition to this, another event handler for the same button (PreviewMouseLeftButtonDown="ImageButtonLeftMouseButtonDown"
in XAML) seems redundant – you can remove it with corresponding event handling proc.
So, the code snippet should look like:
MainWindow()
{
InitializeComponent();
ImageButton.Click += (s, e) => { MessageBox.Show("test button clicked"); };
// ... the rest of the code...
Pertinent to your case (Button
control in ListView
template), refer to this article: WPF ListView with buttons on each line