【发布时间】:2016-06-17 08:42:59
【问题描述】:
实际上,我有两个问题想要解决并整合到我的 wpf 应用程序中。
我有多个具有特定布局的按钮。
<Window.Resources>
<Style x:Key="greenButton" TargetType="Button">
<Setter Property="Background" Value="LightGreen" />
<Setter Property="FontSize" Value="20"/>
<Setter Property="BorderThickness" Value="1"/>
</Style>
...
</Window.Resources>
好的,好的,这是我的按钮:
<Button x:Name="btn100" Grid.Column="0" Grid.Row="2" Style="{StaticResource greenButton}">100</Button>
<Button x:Name="btn101" Grid.Column="0" Grid.Row="3" Style="{StaticResource greenButton}">101</Button>
<Button x:Name="btn102" Grid.Column="0" Grid.Row="4" Style="{StaticResource greenButton}">102</Button>
然后,在单击按钮后,我想触发一个方法,该方法需要按钮的标题
private void btn100_Click(object sender, RoutedEventArgs e)
{
name = (sender as Button).Content.ToString();
doMethod(name);
}
好的。但是我有这么多按钮,所以我想将它们与同一个单击事件处理程序结合在一起。我试过这个:
<StackPanel Button.Click="button_Click" Grid.RowSpan="20">
<Button Grid.Column="0" Grid.Row="0" FontWeight="Bold" BorderBrush="Black" Style="{StaticResource greenButton}">LT 1</Button>
<Button x:Name="btn100" Grid.Column="0" Grid.Row="2" Style="{StaticResource greenButton}">100</Button>
<Button x:Name="btn101" Grid.Column="0" Grid.Row="3" Style="{StaticResource greenButton}">101</Button>
<Button x:Name="btn102" Grid.Column="0" Grid.Row="4" Style="{StaticResource greenButton}">102</Button>
</StackPanel>
我的 c# 代码现在是:
private void button_Click(object sender, RoutedEventArgs e)
{
name= (sender as Button).Content.ToString();
doMethod(name);
}
现在我遇到了两个问题:
- 行对齐不适用于我的按钮。使用堆栈面板,它们现在比我在网格中定义的行更大/更高
- 我不知道按钮名称。它始终为空
谢谢提前帮助。
编辑: 没有In WPF can I attach the same click handler to multiple buttons at once like I can in Javascript/Jquery? 的重复我的解决方案是基于这篇文章,但我有问题更进一步(布局+传输变量)
【问题讨论】:
-
无重复。我的解决方案基于这篇文章,但我更进一步遇到了问题(布局+传输变量)
-
作为说明,当然没有必要引入 StackPanel(这显然会破坏您的布局)。您也可以在 Grid 中指定
Button.Click。
标签: c# wpf event-handling stackpanel