Enabling and disabling buttons in wpf
19,591
Solution 1
This method assumes that the Buttons are on the same Grid, it reverses the Enabled state of every button except of the one doing the clicking.
MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button_Click" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="10,43,0,0" Name="button2" VerticalAlignment="Top" Width="75" Click="button_Click" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="10,76,0,0" Name="button3" VerticalAlignment="Top" Width="75" Click="button_Click" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="10,109,0,0" Name="button4" VerticalAlignment="Top" Width="75" Click="button_Click" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="10,142,0,0" Name="button5" VerticalAlignment="Top" Width="75" Click="button_Click" />
</Grid>
</Window>
MainWindow.xaml.cs
private void button_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
foreach (FrameworkElement item in ((Panel)btn.Parent).Children )
{
if (item is Button)
{
if (btn.Name != item.Name)
item.IsEnabled = !item.IsEnabled;
}
}
}
Solution 2
Write one method that handles all your buttons click. here is an example:
Private Sub ButtonsClick(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles button1.Click ,button2.Click ,button3.Click
button1.IsEnabled = (button1 is sender)
button2.IsEnabled = (button2 is sender)
button3.IsEnabled = (button3 is sender)
End Sub
EDIT: I overlooked the fact that you don't want to enable/disable individual buttons. So I would recommend Mark answer.
Comments
-
Virus about 2 years
I have several
Buttons
on screen. On the click of oneButton
rest all otherButtons
should be disabled. Is there a way to create one single method and set the enabling and disabling allButtons
instead of enabling and disabling individualButtons
.