Button clicks or not
How can I prevent a Button click if there is another clickable Control inside the Button?
I’ve got this question now two times, one at stackoverflow and the other one at MahApps.Metro.
The solution is quite simple. You can handle this behavior at the Button’s click event.
1
2
3
4
5
6
7
8
9
10
11
12
13
private async void ButtonClick(object sender, RoutedEventArgs e)
{
if (e.OriginalSource != sender)
{
// do nothing if we don't hit the button
e.Handled = true;
}
else
{
// yes, we hit the button
await this.ShowMessageAsync(string.Empty, $"Yeah, you clicked the real button!");
}
}
This sample uses the MahApps.Metro
library, so if you want to test this code you must download the NuGet package.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<StackPanel xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"
Margin="20"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Orientation="Vertical">
<Button Height="40"
Margin="0 5"
BorderThickness="0"
Click="ButtonClick"
Style="{DynamicResource SquareButtonStyle}">
<Grid Margin="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
HorizontalAlignment="Center"
VerticalAlignment="Center">
Toggle it
</TextBlock>
<controls:ToggleSwitch Grid.Column="1"
HorizontalAlignment="Center"
VerticalAlignment="Center"
IsChecked="True"
OffLabel=""
OnLabel=""
Style="{StaticResource MahApps.Metro.Styles.ToggleSwitch.Win10}" />
</Grid>
</Button>
<Button Height="40"
Margin="0 5"
BorderThickness="0"
Click="ButtonClick"
Style="{DynamicResource SquareButtonStyle}">
<Grid Margin="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
HorizontalAlignment="Center"
VerticalAlignment="Center">
Counter Button
</TextBlock>
<controls:NumericUpDown Grid.Column="1" Width="100" />
</Grid>
</Button>
</StackPanel>
This post is licensed under CC BY 4.0 by the author.