实际上,我有两个问题需要解决,并在我的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?的重复我的解决方案是基于这篇文章但我有进一步的问题(布局+转移变量)
答案 0 :(得分:3)
当您将Button.Click
处理程序分配给StackPanel时,处理程序方法的sender参数不是Button,因此(sender as Button)
返回null。
您可以改为编写(e.OriginalSource as Button)
,通过它可以更简单地将Click处理程序分配给您样式中EventSetter
的所有按钮:
<Style x:Key="greenButton" TargetType="Button">
...
<EventSetter Event="Click" Handler="button_Click"/>
</Style>
答案 1 :(得分:1)
我认为,发送者在这种情况下是StackPanel。尝试使用:
string name = (e.OriginalSource as Button)?.Content.ToString();