我有几个Buttons
在屏幕上。单击一个休息时,应禁用Button
所有其他休息。Buttons
有没有办法创建一个方法并设置启用和禁用 allButtons
而不是启用和禁用单个Buttons
.
问问题
19595 次
4 回答
4
此方法假定按钮位于同一个网格上,它会反转每个按钮的启用状态,但单击的按钮除外。
主窗口.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>
主窗口.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;
}
}
}
于 2013-01-01T09:08:43.710 回答
1
编写一种处理所有按钮单击的方法。这是一个例子:
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
编辑:我忽略了您不想启用/禁用单个按钮的事实。所以我会推荐马克回答。
于 2013-01-01T09:12:51.113 回答
0
我有一个想法,首先创建一个禁用所有按钮的方法。每当单击任何按钮时首先调用该方法,以便禁用所有按钮,然后为该单个按钮单击事件处理程序方法启用您刚刚单击的按钮。
于 2013-01-01T08:42:29.837 回答
0
我用 Christian 在评论中提供的链接完成了 Mark Hall 的回答。你可能会喜欢。
按钮无需位于一个 Grid 中或处理其所有单击事件。
在父窗口中处理PreviewMouseLeftButtonDown
事件,而不是:
void window_PreviewMouseLeftButtonDown(object sender, MouseEventArgs e)
{
Window win = sender as Window;
if (e.OriginalSource is Button)
{
Button btn=(Button)e.Source;
foreach(Button button0 in FindVisualChildren<Button>(win))
{
if (btn != button0)
button0.IsEnable = false;
}
}
}
它使用以下方法。请参阅按类型查找 WPF 窗口中的所有控件
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
于 2013-01-01T11:20:59.170 回答