实际上,我有两个问题想解决并在我的 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? 没有重复项我的解决方案基于这篇文章,但我在更进一步时遇到了问题(布局 + 传输变量)
请您参考如下方法:
当您将 Button.Click 处理程序分配给 StackPanel 时,处理程序方法的 sender 参数不是 Button,因此 (sender as Button) 返回 null。
您可以改为编写 (e.OriginalSource as Button),因为通过样式中的 EventSetter 将 Click 处理程序分配给所有按钮可能更简单:
<Style x:Key="greenButton" TargetType="Button">
...
<EventSetter Event="Click" Handler="button_Click"/>
</Style>
